repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Skyscanner/SkyFloatingLabelTextField
|
Sources/SkyFloatingLabelTextFieldWithIcon.swift
|
2
|
11712
|
// Copyright 2016-2019 Skyscanner Ltd
//
// 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
/**
Identify the type of icon.
- font: Set your icon by setting the font of iconLabel
- image: Set your icon by setting the image of iconImageView
*/
public enum IconType: Int {
case font
case image
}
/**
A beautiful and flexible textfield implementation with support for icon, title label, error message and placeholder.
*/
open class SkyFloatingLabelTextFieldWithIcon: SkyFloatingLabelTextField {
@IBInspectable
var iconTypeValue: Int {
get {
return self.iconType.rawValue
}
set(iconIndex) {
self.iconType = IconType(rawValue: iconIndex) ?? .font
}
}
open var iconType: IconType = .font {
didSet {
updateIconViewHiddenState()
}
}
/// A UIImageView value that identifies the view used to display the icon
open var iconImageView: UIImageView!
/// A UIImage value that determines the image that the icon is using
@IBInspectable
dynamic open var iconImage: UIImage? {
didSet {
// Show a warning if setting an image while the iconType is IconType.font
if self.iconType == .font { NSLog("WARNING - Did set iconImage when the iconType is set to IconType.font. The image will not be displayed.") } // swiftlint:disable:this line_length
iconImageView?.image = iconImage
}
}
/// A Bool value that determines if the UIImage should be templated or not
@IBInspectable
dynamic open var templateImage: Bool = true {
didSet {
if templateImage {
let templatedOriginalImage = self.iconImageView.image?
.withRenderingMode(.alwaysTemplate)
self.iconImageView.image = templatedOriginalImage
}
}
}
/// A UILabel value that identifies the label used to display the icon
open var iconLabel: UILabel!
/// A UIFont value that determines the font that the icon is using
@objc dynamic open var iconFont: UIFont? {
didSet {
iconLabel?.font = iconFont
}
}
/// A String value that determines the text used when displaying the icon
@IBInspectable
open var iconText: String? {
didSet {
// Show a warning if setting an icon text while the iconType is IconType.image
if self.iconType == .image { NSLog("WARNING - Did set iconText when the iconType is set to IconType.image. The icon with the specified text will not be displayed.") } // swiftlint:disable:this line_length
iconLabel?.text = iconText
}
}
/// A UIColor value that determines the color of the icon in the normal state
@IBInspectable
dynamic open var iconColor: UIColor = UIColor.gray {
didSet {
if self.iconType == .font {
updateIconLabelColor()
}
if self.iconType == .image && self.templateImage {
updateImageViewTintColor()
}
}
}
/// A UIColor value that determines the color of the icon when the control is selected
@IBInspectable
dynamic open var selectedIconColor: UIColor = UIColor.gray {
didSet {
updateIconLabelColor()
}
}
/// A float value that determines the width of the icon
@IBInspectable
dynamic open var iconWidth: CGFloat = 20 {
didSet {
updateFrame()
}
}
/**
A float value that determines the left margin of the icon.
Use this value to position the icon more precisely horizontally.
*/
@IBInspectable
dynamic open var iconMarginLeft: CGFloat = 4 {
didSet {
updateFrame()
}
}
/**
A float value that determines the bottom margin of the icon.
Use this value to position the icon more precisely vertically.
*/
@IBInspectable
dynamic open var iconMarginBottom: CGFloat = 4 {
didSet {
updateFrame()
}
}
/**
A float value that determines the rotation in degrees of the icon.
Use this value to rotate the icon in either direction.
*/
@IBInspectable
open var iconRotationDegrees: Double = 0 {
didSet {
iconLabel.transform = CGAffineTransform(rotationAngle: CGFloat(iconRotationDegrees * .pi / 180.0))
iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(iconRotationDegrees * .pi / 180.0))
}
}
// MARK: Initializers
/**
Initializes the control
- parameter type the type of icon
*/
convenience public init(frame: CGRect, iconType: IconType) {
self.init(frame: frame)
self.iconType = iconType
updateIconViewHiddenState()
}
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
createIcon()
updateIconViewHiddenState()
}
/**
Intialzies the control by deserializing it
- parameter aDecoder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createIcon()
updateIconViewHiddenState()
}
// MARK: Creating the icon
/// Creates the both icon label and icon image view
fileprivate func createIcon() {
createIconLabel()
createIconImageView()
}
// MARK: Creating the icon label
/// Creates the icon label
fileprivate func createIconLabel() {
let iconLabel = UILabel()
iconLabel.backgroundColor = UIColor.clear
iconLabel.textAlignment = .center
iconLabel.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
self.iconLabel = iconLabel
addSubview(iconLabel)
updateIconLabelColor()
}
// MARK: Creating the icon image view
/// Creates the icon image view
fileprivate func createIconImageView() {
let iconImageView = UIImageView()
iconImageView.backgroundColor = .clear
iconImageView.contentMode = .scaleAspectFit
iconImageView.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
self.iconImageView = iconImageView
self.templateImage = true
addSubview(iconImageView)
}
// MARK: Set icon hidden property
/// Shows the corresponding icon depending on iconType property
fileprivate func updateIconViewHiddenState() {
switch iconType {
case .font:
self.iconLabel.isHidden = false
self.iconImageView.isHidden = true
case .image:
self.iconLabel.isHidden = true
self.iconImageView.isHidden = false
}
}
// MARK: Handling the icon color
/// Update the colors for the control. Override to customize colors.
override open func updateColors() {
super.updateColors()
if self.iconType == .font {
updateIconLabelColor()
}
if self.iconType == .image && self.templateImage {
updateImageViewTintColor()
}
}
fileprivate func updateImageViewTintColor() {
if !isEnabled {
iconImageView.tintColor = disabledColor
} else if hasErrorMessage {
iconImageView.tintColor = errorColor
} else {
iconImageView.tintColor = editingOrSelected ? selectedIconColor : iconColor
}
}
fileprivate func updateIconLabelColor() {
if !isEnabled {
iconLabel?.textColor = disabledColor
} else if hasErrorMessage {
iconLabel?.textColor = errorColor
} else {
iconLabel?.textColor = editingOrSelected ? selectedIconColor : iconColor
}
}
// MARK: Custom layout overrides
/**
Calculate the bounds for the textfield component of the control.
Override to create a custom size textbox in the control.
- parameter bounds: The current bounds of the textfield component
- returns: The rectangle that the textfield component should render in
*/
override open func textRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.textRect(forBounds: bounds)
if isLTRLanguage {
rect.origin.x += CGFloat(iconWidth + iconMarginLeft)
} else {
rect.origin.x -= CGFloat(iconWidth + iconMarginLeft)
}
rect.size.width -= CGFloat(iconWidth + iconMarginLeft)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.editingRect(forBounds: bounds)
if isLTRLanguage {
rect.origin.x += CGFloat(iconWidth + iconMarginLeft)
} else {
// don't change the editing field X position for RTL languages
}
rect.size.width -= CGFloat(iconWidth + iconMarginLeft)
return rect
}
/**
Calculates the bounds for the placeholder component of the control.
Override to create a custom size textbox in the control.
- parameter bounds: The current bounds of the placeholder component
- returns: The rectangle that the placeholder component should render in
*/
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.placeholderRect(forBounds: bounds)
if isLTRLanguage {
rect.origin.x += CGFloat(iconWidth + iconMarginLeft)
} else {
// don't change the editing field X position for RTL languages
}
rect.size.width -= CGFloat(iconWidth + iconMarginLeft)
return rect
}
/// Invoked by layoutIfNeeded automatically
override open func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
fileprivate func updateFrame() {
let textWidth: CGFloat = bounds.size.width
if isLTRLanguage {
iconLabel.frame = CGRect(
x: 0,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
iconImageView.frame = CGRect(
x: 0,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
} else {
iconLabel.frame = CGRect(
x: textWidth - iconWidth,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
iconImageView.frame = CGRect(
x: textWidth - iconWidth,
y: bounds.size.height - textHeight() - iconMarginBottom,
width: iconWidth,
height: textHeight()
)
}
}
}
|
apache-2.0
|
2b4b8e9aae5d4d0100f81414eec628d9
| 31.991549 | 216 | 0.623207 | 5.285199 | false | false | false | false |
safx/EJDB-Swift
|
Tests/EJDB_SwiftTests.swift
|
1
|
1827
|
//
// EJDB_SwiftTests.swift
// EJDB-SwiftTests
//
// Created by Safx Developer on 2015/07/26.
// Copyright © 2015年 Safx Developers. All rights reserved.
//
import XCTest
@testable import EJDBSwift
class EJDB_SwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, [.UserDomainMask], true);
let dbPath = paths[0] + "/addressbook.db"
let db = Database()
db.open(dbPath, mode: [.Writer, .Create, .Truncate])
let col = Collection(name: "foo", database: db)
let b1: BSON = [
"address": "Somewhere",
"name": "foreign",
"age": [10, 20, 30],
"hoge": false
]
col.save(b1)
let b2: BSON = [
"address": "Canada",
"name": "fooobar",
"age": [14, 20],
"hoge": true
]
col.save(b2)
let b3: BSON = [
"address": "Canada",
"name": "barrrr",
"age": [1024],
"hoge": true
]
col.save(b3)
let qry = Query(query: BSON(query: [ "name": ["$begin": "fo"] ]), database: db)
let res = col.query(qry).map { $0.object }
print(res)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
dca286278fdced9d1507cbc4f7e018a4
| 25.823529 | 111 | 0.532895 | 4.008791 | false | true | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/UI/SidebarCell.swift
|
1
|
4077
|
/*
* Copyright 2019 Google LLC. 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 third_party_objective_c_material_components_ios_components_Ink_Ink
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// Cell used in the sidebar to display a menu option with a title and icon.
class SidebarCell: UICollectionViewCell {
// MARK: - Constants
let iconDimension: CGFloat = 24.0
let iconPadding: CGFloat = 16.0
let titlePadding: CGFloat = 72.0
let sidebarIconColor = UIColor(red: 0.451, green: 0.451, blue: 0.451, alpha: 1.0)
// MARK: - Properties
let iconView = UIImageView()
let titleLabel = UILabel()
let accessoryIconView = UIImageView()
private let inkView = MDCInkView()
private let statusBarCoverView = UIView()
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureCell()
}
// MARK: - Private
private func configureCell() {
isAccessibilityElement = true
accessibilityTraits = .button
inkView.inkColor = UIColor(white: 0, alpha: 0.1)
inkView.frame = contentView.bounds
contentView.addSubview(inkView)
// Icon
contentView.addSubview(iconView)
iconView.tintColor = sidebarIconColor
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
iconView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: iconPadding).isActive = true
iconView.widthAnchor.constraint(equalToConstant: iconDimension).isActive = true
iconView.heightAnchor.constraint(equalToConstant: iconDimension).isActive = true
// Title label
contentView.addSubview(titleLabel)
titleLabel.textColor = .black
titleLabel.font = MDCTypography.body2Font()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerYAnchor.constraint(equalTo: iconView.centerYAnchor).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor,
constant: titlePadding).isActive = true
// Accessory icon view
contentView.addSubview(accessoryIconView)
accessoryIconView.tintColor = sidebarIconColor
accessoryIconView.translatesAutoresizingMaskIntoConstraints = false
accessoryIconView.centerYAnchor.constraint(
equalTo: centerYAnchor).isActive = true
accessoryIconView.trailingAnchor.constraint(
equalTo: trailingAnchor, constant: -iconPadding).isActive = true
accessoryIconView.widthAnchor.constraint(equalToConstant: iconDimension).isActive = true
accessoryIconView.heightAnchor.constraint(equalToConstant: iconDimension).isActive = true
}
// MARK: Ink
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
inkView.startTouchBeganAnimation(at: touch.location(in: contentView), completion: nil)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if let touch = touches.first {
inkView.startTouchEndedAnimation(at: touch.location(in: contentView), completion: nil)
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
inkView.cancelAllAnimations(animated: true)
}
}
|
apache-2.0
|
a81040a5e1ecb34e41a46a0aa497922e
| 35.079646 | 100 | 0.739269 | 4.611991 | false | false | false | false |
chrisdhaan/CDMarkdownKit
|
Source/CDMarkdownLink.swift
|
1
|
4802
|
//
// CDMarkdownLink.swift
// CDMarkdownKit
//
// Created by Christopher de Haan on 11/7/16.
//
// Copyright © 2016-2022 Christopher de Haan <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
open class CDMarkdownLink: CDMarkdownLinkElement {
fileprivate static let regex = "[^!{1}]\\[([^\\[]*?)\\]\\(([^\\)]*)\\)"
open var font: CDFont?
open var color: CDColor?
open var backgroundColor: CDColor?
open var paragraphStyle: NSParagraphStyle?
open var regex: String {
return CDMarkdownLink.regex
}
open func regularExpression() throws -> NSRegularExpression {
return try NSRegularExpression(pattern: regex,
options: .dotMatchesLineSeparators)
}
public init(font: CDFont? = nil,
color: CDColor? = CDColor.blue,
backgroundColor: CDColor? = nil,
paragraphStyle: NSParagraphStyle? = nil) {
self.font = font
self.color = color
self.backgroundColor = backgroundColor
self.paragraphStyle = paragraphStyle
}
open func formatText(_ attributedString: NSMutableAttributedString,
range: NSRange,
link: String) {
guard let encodedLink = link.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
else {
return
}
guard let url = URL(string: link) ?? URL(string: encodedLink) else { return }
attributedString.addLink(url,
toRange: range)
}
open func match(_ match: NSTextCheckingResult,
attributedString: NSMutableAttributedString) {
guard match.numberOfRanges == 3 else { return }
let nsString = attributedString.string as NSString
let linkStartInResult = nsString.range(of: "(",
options: .backwards,
range: match.range).location
let linkRange = NSRange(location: linkStartInResult,
length: match.range.length + match.range.location - linkStartInResult - 1)
let linkURLString = nsString.substring(with: NSRange(location: linkRange.location + 1,
length: linkRange.length - 1))
// deleting trailing markdown
// needs to be called before formattingBlock to support modification of length
attributedString.deleteCharacters(in: NSRange(location: linkRange.location - 1,
length: linkRange.length + 2))
// deleting leading markdown
// needs to be called before formattingBlock to provide a stable range
attributedString.deleteCharacters(in: NSRange(location: match.range.location + 1,
length: 1))
let formatRange = NSRange(location: match.range.location + 1,
length: linkStartInResult - match.range.location - 3)
formatText(attributedString,
range: formatRange,
link: linkURLString)
addAttributes(attributedString,
range: formatRange,
link: linkURLString)
}
open func addAttributes(_ attributedString: NSMutableAttributedString,
range: NSRange,
link: String) {
attributedString.addAttributes(attributes,
range: range)
}
}
|
mit
|
67b4effe00751890c7ace3c02287f024
| 41.114035 | 110 | 0.608415 | 5.299117 | false | false | false | false |
afarber/ios-newbie
|
Tops1/Tops1/ViewModels/TopViewModel.swift
|
1
|
4787
|
//
// TopViewModel.swift
// Tops1
//
// Created by Alexander Farber on 18.06.21.
//
import Foundation
import Combine
import CoreData
class TopViewModel: NSObject, ObservableObject {
let urls = [
"en" : URL(string: "https://wordsbyfarber.com/ws/top"),
"de" : URL(string: "https://wortefarbers.de/ws/top"),
"ru" : URL(string: "https://slova.de/ws/top")
]
var cancellables = Set<AnyCancellable>()
@Published var topEntities: [TopEntity] = []
override init() {
super.init()
UserDefaults.standard.addObserver(self,
forKeyPath: "language",
options: NSKeyValueObservingOptions.new,
context: nil)
let language = UserDefaults.standard.string(forKey: "language") ?? "en"
updateTopEntities(language: language)
fetchTopModels(language: language)
}
deinit {
UserDefaults.standard.removeObserver(self, forKeyPath: "language")
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
guard keyPath == "language",
let change = change,
let language = change[.newKey] as? String else {
return
}
updateTopEntities(language: language)
fetchTopModels(language: language)
}
func updateTopEntities(language:String) {
print("updateTopEntities language=\(language)")
let viewContext = PersistenceController.shared.container.viewContext
let request = NSFetchRequest<TopEntity>(entityName: "TopEntity")
request.sortDescriptors = [ NSSortDescriptor(keyPath: \TopEntity.elo, ascending: false) ]
request.predicate = NSPredicate(format: "language = %@", language)
do {
topEntities = try viewContext.fetch(request)
} catch let error {
print("Error fetching. \(error)")
}
}
func fetchTopModels(language:String) {
print("fetchTopModels language=\(language)")
// as? means "this might be nil"
guard let url = urls[language] as? URL else { return }
URLSession.shared.dataTaskPublisher(for: url)
.tryMap(handleOutput)
.decode(type: TopResponse.self, decoder: JSONDecoder())
.sink { completion in
print("fetchTopModels completion=\(completion)")
} receiveValue: { fetchedTops in
PersistenceController.shared.container.performBackgroundTask { backgroundContext in
backgroundContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
backgroundContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform {
for topModel in fetchedTops.data {
//print(topModel)
let topEntity = TopEntity(context: backgroundContext)
topEntity.language = language
topEntity.uid = Int32(topModel.id)
topEntity.elo = Int32(topModel.elo)
topEntity.given = topModel.given
topEntity.motto = topModel.motto
topEntity.photo = topModel.photo
topEntity.avg_score = topModel.avg_score ?? 0.0
topEntity.avg_time = topModel.avg_time
}
if (backgroundContext.hasChanges) {
do {
try backgroundContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
DispatchQueue.main.async { [weak self] in
self?.updateTopEntities(language: language)
}
}
}
}
}
.store(in: &cancellables)
}
func handleOutput(output: URLSession.DataTaskPublisher.Output) throws -> Data {
guard
let response = output.response as? HTTPURLResponse,
response.statusCode >= 200,
response.statusCode < 300
else {
throw URLError(.badServerResponse)
}
return output.data
}
}
|
unlicense
|
1ab7737845cbf750f9cdc5001d8ec0e3
| 37.918699 | 99 | 0.524128 | 5.521338 | false | false | false | false |
kevinmbeaulieu/Signal-iOS
|
Signal/src/ViewControllers/CallViewController.swift
|
1
|
39998
|
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import WebRTC
import PromiseKit
// TODO: Add category so that button handlers can be defined where button is created.
// TODO: Ensure buttons enabled & disabled as necessary.
@objc(OWSCallViewController)
class CallViewController: UIViewController, CallObserver, CallServiceObserver, RTCEAGLVideoViewDelegate {
let TAG = "[CallViewController]"
// Dependencies
let callUIAdapter: CallUIAdapter
let contactsManager: OWSContactsManager
// MARK: Properties
var thread: TSContactThread!
var call: SignalCall!
var hasDismissed = false
// MARK: Views
var hasConstraints = false
var blurView: UIVisualEffectView!
var dateFormatter: DateFormatter?
// MARK: Contact Views
var contactNameLabel: UILabel!
var contactAvatarView: AvatarImageView!
var callStatusLabel: UILabel!
var callDurationTimer: Timer?
// MARK: Ongoing Call Controls
var ongoingCallView: UIView!
var hangUpButton: UIButton!
var speakerPhoneButton: UIButton!
var audioModeMuteButton: UIButton!
var audioModeVideoButton: UIButton!
var videoModeMuteButton: UIButton!
var videoModeVideoButton: UIButton!
// TODO: Later, we'll re-enable the text message button
// so users can send and read messages during a
// call.
// var textMessageButton: UIButton!
// MARK: Incoming Call Controls
var incomingCallView: UIView!
var acceptIncomingButton: UIButton!
var declineIncomingButton: UIButton!
// MARK: Video Views
var remoteVideoView: RTCEAGLVideoView!
var localVideoView: RTCCameraPreviewView!
weak var localVideoTrack: RTCVideoTrack?
weak var remoteVideoTrack: RTCVideoTrack?
var remoteVideoSize: CGSize! = CGSize.zero
var remoteVideoConstraints: [NSLayoutConstraint] = []
var localVideoConstraints: [NSLayoutConstraint] = []
var shouldRemoteVideoControlsBeHidden = false {
didSet {
updateCallUI(callState: call.state)
}
}
// MARK: Settings Nag Views
var isShowingSettingsNag = false {
didSet {
if oldValue != isShowingSettingsNag {
updateCallUI(callState: call.state)
}
}
}
var settingsNagView: UIView!
var settingsNagDescriptionLabel: UILabel!
// MARK: Initializers
required init?(coder aDecoder: NSCoder) {
contactsManager = Environment.getCurrent().contactsManager
callUIAdapter = Environment.getCurrent().callUIAdapter
super.init(coder: aDecoder)
observeNotifications()
}
required init() {
contactsManager = Environment.getCurrent().contactsManager
callUIAdapter = Environment.getCurrent().callUIAdapter
super.init(nibName: nil, bundle: nil)
observeNotifications()
}
func observeNotifications() {
NotificationCenter.default.addObserver(self,
selector:#selector(didBecomeActive),
name:NSNotification.Name.UIApplicationDidBecomeActive,
object:nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didBecomeActive() {
shouldRemoteVideoControlsBeHidden = false
}
// MARK: View Lifecycle
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
UIDevice.current.isProximityMonitoringEnabled = false
callDurationTimer?.invalidate()
callDurationTimer = nil
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.isProximityMonitoringEnabled = true
updateCallUI(callState: call.state)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let thread = self.thread else {
Logger.error("\(TAG) tried to show call call without specifying thread.")
showCallFailed(error: OWSErrorMakeAssertionError())
return
}
createViews()
contactNameLabel.text = contactsManager.displayName(forPhoneIdentifier: thread.contactIdentifier())
contactAvatarView.image = OWSAvatarBuilder.buildImage(for: thread, contactsManager: contactsManager)
assert(call != nil)
// Subscribe for future call updates
call.addObserverAndSyncState(observer: self)
Environment.getCurrent().callService.addObserverAndSyncState(observer:self)
}
// MARK: - Create Views
func createViews() {
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(OWSAnyTouchGestureRecognizer(target:self,
action:#selector(didTouchRootView)))
// Dark blurred background.
let blurEffect = UIBlurEffect(style: .dark)
blurView = UIVisualEffectView(effect: blurEffect)
blurView.isUserInteractionEnabled = false
self.view.addSubview(blurView)
// Create the video views first, as they are under the other views.
createVideoViews()
createContactViews()
createOngoingCallControls()
createIncomingCallControls()
createSettingsNagViews()
}
func didTouchRootView(sender: UIGestureRecognizer) {
if !remoteVideoView.isHidden {
shouldRemoteVideoControlsBeHidden = !shouldRemoteVideoControlsBeHidden
}
}
func createVideoViews() {
remoteVideoView = RTCEAGLVideoView()
remoteVideoView.delegate = self
remoteVideoView.isUserInteractionEnabled = false
localVideoView = RTCCameraPreviewView()
remoteVideoView.isHidden = true
localVideoView.isHidden = true
self.view.addSubview(remoteVideoView)
self.view.addSubview(localVideoView)
}
func createContactViews() {
contactNameLabel = UILabel()
contactNameLabel.font = UIFont.ows_lightFont(withSize:ScaleFromIPhone5To7Plus(32, 40))
contactNameLabel.textColor = UIColor.white
contactNameLabel.layer.shadowOffset = CGSize.zero
contactNameLabel.layer.shadowOpacity = 0.35
contactNameLabel.layer.shadowRadius = 4
self.view.addSubview(contactNameLabel)
callStatusLabel = UILabel()
callStatusLabel.font = UIFont.ows_regularFont(withSize:ScaleFromIPhone5To7Plus(19, 25))
callStatusLabel.textColor = UIColor.white
callStatusLabel.layer.shadowOffset = CGSize.zero
callStatusLabel.layer.shadowOpacity = 0.35
callStatusLabel.layer.shadowRadius = 4
self.view.addSubview(callStatusLabel)
contactAvatarView = AvatarImageView()
self.view.addSubview(contactAvatarView)
}
func createSettingsNagViews() {
settingsNagView = UIView()
settingsNagView.isHidden = true
self.view.addSubview(settingsNagView)
let viewStack = UIView()
settingsNagView.addSubview(viewStack)
viewStack.autoPinWidthToSuperview()
viewStack.autoVCenterInSuperview()
settingsNagDescriptionLabel = UILabel()
settingsNagDescriptionLabel.text = NSLocalizedString("CALL_VIEW_SETTINGS_NAG_DESCRIPTION_ALL",
comment: "Reminder to the user of the benefits of enabling CallKit and disabling CallKit privacy.")
settingsNagDescriptionLabel.font = UIFont.ows_regularFont(withSize:ScaleFromIPhone5To7Plus(16, 18))
settingsNagDescriptionLabel.textColor = UIColor.white
settingsNagDescriptionLabel.numberOfLines = 0
settingsNagDescriptionLabel.lineBreakMode = .byWordWrapping
viewStack.addSubview(settingsNagDescriptionLabel)
settingsNagDescriptionLabel.autoPinWidthToSuperview()
settingsNagDescriptionLabel.autoPinEdge(toSuperviewEdge:.top)
let buttonHeight = ScaleFromIPhone5To7Plus(35, 45)
let buttonFont = UIFont.ows_regularFont(withSize:ScaleFromIPhone5To7Plus(14, 18))
let buttonCornerRadius = CGFloat(4)
let descriptionVSpacingHeight = ScaleFromIPhone5To7Plus(30, 60)
let callSettingsButton = UIButton()
callSettingsButton.setTitle(NSLocalizedString("CALL_VIEW_SETTINGS_NAG_SHOW_CALL_SETTINGS",
comment: "Label for button that shows the privacy settings"), for:.normal)
callSettingsButton.setTitleColor(UIColor.white, for:.normal)
callSettingsButton.titleLabel!.font = buttonFont
callSettingsButton.addTarget(self, action:#selector(didPressShowCallSettings), for:.touchUpInside)
callSettingsButton.backgroundColor = UIColor.ows_signalBrandBlue()
callSettingsButton.layer.cornerRadius = buttonCornerRadius
callSettingsButton.clipsToBounds = true
viewStack.addSubview(callSettingsButton)
callSettingsButton.autoSetDimension(.height, toSize:buttonHeight)
callSettingsButton.autoPinWidthToSuperview()
callSettingsButton.autoPinEdge(.top, to:.bottom, of:settingsNagDescriptionLabel, withOffset:descriptionVSpacingHeight)
let notNowButton = UIButton()
notNowButton.setTitle(NSLocalizedString("CALL_VIEW_SETTINGS_NAG_NOT_NOW_BUTTON",
comment: "Label for button that dismiss the call view's settings nag."), for:.normal)
notNowButton.setTitleColor(UIColor.white, for:.normal)
notNowButton.titleLabel!.font = buttonFont
notNowButton.addTarget(self, action:#selector(didPressDismissNag), for:.touchUpInside)
notNowButton.backgroundColor = UIColor.ows_signalBrandBlue()
notNowButton.layer.cornerRadius = buttonCornerRadius
notNowButton.clipsToBounds = true
viewStack.addSubview(notNowButton)
notNowButton.autoSetDimension(.height, toSize:buttonHeight)
notNowButton.autoPinWidthToSuperview()
notNowButton.autoPinEdge(toSuperviewEdge:.bottom)
notNowButton.autoPinEdge(.top, to:.bottom, of:callSettingsButton, withOffset:12)
}
func buttonSize() -> CGFloat {
return ScaleFromIPhone5To7Plus(84, 108)
}
func buttonInset() -> CGFloat {
return ScaleFromIPhone5To7Plus(7, 9)
}
func createOngoingCallControls() {
// textMessageButton = createButton(imageName:"message-active-wide",
// action:#selector(didPressTextMessage))
speakerPhoneButton = createButton(imageName:"speaker-inactive-wide",
action:#selector(didPressSpeakerphone))
hangUpButton = createButton(imageName:"hangup-active-wide",
action:#selector(didPressHangup))
audioModeMuteButton = createButton(imageName:"mute-unselected-wide",
action:#selector(didPressMute))
videoModeMuteButton = createButton(imageName:"video-mute-unselected",
action:#selector(didPressMute))
audioModeVideoButton = createButton(imageName:"video-inactive-wide",
action:#selector(didPressVideo))
videoModeVideoButton = createButton(imageName:"video-video-unselected",
action:#selector(didPressVideo))
setButtonSelectedImage(button: audioModeMuteButton, imageName: "mute-selected-wide")
setButtonSelectedImage(button: videoModeMuteButton, imageName: "video-mute-selected")
setButtonSelectedImage(button: audioModeVideoButton, imageName: "video-active-wide")
setButtonSelectedImage(button: videoModeVideoButton, imageName: "video-video-selected")
setButtonSelectedImage(button: speakerPhoneButton, imageName: "speaker-active-wide")
ongoingCallView = createContainerForCallControls(controlGroups : [
[audioModeMuteButton, speakerPhoneButton, audioModeVideoButton ],
[videoModeMuteButton, hangUpButton, videoModeVideoButton ]
])
}
func setButtonSelectedImage(button: UIButton, imageName: String) {
let image = UIImage(named:imageName)
assert(image != nil)
button.setImage(image, for:.selected)
}
func createIncomingCallControls() {
acceptIncomingButton = createButton(imageName:"call-active-wide",
action:#selector(didPressAnswerCall))
declineIncomingButton = createButton(imageName:"hangup-active-wide",
action:#selector(didPressDeclineCall))
incomingCallView = createContainerForCallControls(controlGroups : [
[acceptIncomingButton, declineIncomingButton ]
])
}
func createContainerForCallControls(controlGroups: [[UIView]]) -> UIView {
let containerView = UIView()
self.view.addSubview(containerView)
var rows: [UIView] = []
for controlGroup in controlGroups {
rows.append(rowWithSubviews(subviews:controlGroup))
}
let rowspacing = ScaleFromIPhone5To7Plus(6, 7)
var prevRow: UIView?
for row in rows {
containerView.addSubview(row)
row.autoHCenterInSuperview()
if prevRow != nil {
row.autoPinEdge(.top, to:.bottom, of:prevRow!, withOffset:rowspacing)
}
prevRow = row
}
containerView.setContentHuggingVerticalHigh()
rows.first!.autoPinEdge(toSuperviewEdge:.top)
rows.last!.autoPinEdge(toSuperviewEdge:.bottom)
return containerView
}
func createButton(imageName: String, action: Selector) -> UIButton {
let image = UIImage(named:imageName)
assert(image != nil)
let button = UIButton()
button.setImage(image, for:.normal)
button.imageEdgeInsets = UIEdgeInsets(top: buttonInset(),
left: buttonInset(),
bottom: buttonInset(),
right: buttonInset())
button.addTarget(self, action:action, for:.touchUpInside)
button.autoSetDimension(.width, toSize:buttonSize())
button.autoSetDimension(.height, toSize:buttonSize())
return button
}
// Creates a row containing a given set of subviews.
func rowWithSubviews(subviews: [UIView]) -> UIView {
let row = UIView()
row.setContentHuggingVerticalHigh()
row.autoSetDimension(.height, toSize:buttonSize())
if subviews.count > 1 {
// If there's more than one subview in the row,
// space them evenly within the row.
var lastSubview: UIView?
for subview in subviews {
row.addSubview(subview)
subview.setContentHuggingHorizontalHigh()
subview.autoVCenterInSuperview()
if lastSubview != nil {
let spacer = UIView()
spacer.isHidden = true
row.addSubview(spacer)
spacer.autoPinEdge(.left, to:.right, of:lastSubview!)
spacer.autoPinEdge(.right, to:.left, of:subview)
spacer.setContentHuggingHorizontalLow()
spacer.autoVCenterInSuperview()
if subviews.count == 2 {
// special case to hardcode the spacer's size when there is only 1 spacer.
spacer.autoSetDimension(.width, toSize: ScaleFromIPhone5To7Plus(46, 60))
} else {
spacer.autoSetDimension(.width, toSize: ScaleFromIPhone5To7Plus(3, 5))
}
}
lastSubview = subview
}
subviews.first!.autoPinEdge(toSuperviewEdge:.left)
subviews.last!.autoPinEdge(toSuperviewEdge:.right)
} else if subviews.count == 1 {
// If there's only one subview in this row, center it.
let subview = subviews.first!
row.addSubview(subview)
subview.autoVCenterInSuperview()
subview.autoPinWidthToSuperview()
}
return row
}
// MARK: - Layout
override func updateViewConstraints() {
if !hasConstraints {
// We only want to create our constraints once.
//
// Note that constraints are also created elsewhere.
// This only creates the constraints for the top-level contents of the view.
hasConstraints = true
let topMargin = CGFloat(40)
let contactHMargin = CGFloat(30)
let contactVSpacing = CGFloat(3)
let ongoingHMargin = ScaleFromIPhone5To7Plus(46, 72)
let incomingHMargin = ScaleFromIPhone5To7Plus(46, 72)
let settingsNagHMargin = CGFloat(30)
let ongoingBottomMargin = ScaleFromIPhone5To7Plus(23, 41)
let incomingBottomMargin = CGFloat(41)
let settingsNagBottomMargin = CGFloat(41)
let avatarTopSpacing = ScaleFromIPhone5To7Plus(25, 50)
// The buttons have built-in 10% margins, so to appear centered
// the avatar's bottom spacing should be a bit less.
let avatarBottomSpacing = ScaleFromIPhone5To7Plus(18, 41)
// Layout of the local video view is a bit unusual because
// although the view is square, it will be used
let videoPreviewHMargin = CGFloat(0)
// Dark blurred background.
blurView.autoPinEdgesToSuperviewEdges()
localVideoView.autoPinEdge(toSuperviewEdge:.right, withInset:videoPreviewHMargin)
localVideoView.autoPinEdge(toSuperviewEdge:.top, withInset:topMargin)
let localVideoSize = ScaleFromIPhone5To7Plus(80, 100)
localVideoView.autoSetDimension(.width, toSize:localVideoSize)
localVideoView.autoSetDimension(.height, toSize:localVideoSize)
contactNameLabel.autoPinEdge(toSuperviewEdge:.top, withInset:topMargin)
contactNameLabel.autoPinEdge(toSuperviewEdge:.left, withInset:contactHMargin)
contactNameLabel.setContentHuggingVerticalHigh()
callStatusLabel.autoPinEdge(.top, to:.bottom, of:contactNameLabel, withOffset:contactVSpacing)
callStatusLabel.autoPinEdge(toSuperviewEdge:.left, withInset:contactHMargin)
callStatusLabel.setContentHuggingVerticalHigh()
contactAvatarView.autoPinEdge(.top, to:.bottom, of:callStatusLabel, withOffset:+avatarTopSpacing)
contactAvatarView.autoPinEdge(.bottom, to:.top, of:ongoingCallView, withOffset:-avatarBottomSpacing)
contactAvatarView.autoHCenterInSuperview()
// Stretch that avatar to fill the available space.
contactAvatarView.setContentHuggingLow()
contactAvatarView.setCompressionResistanceLow()
// Preserve square aspect ratio of contact avatar.
contactAvatarView.autoMatch(.width, to:.height, of:contactAvatarView)
// Ongoing call controls
ongoingCallView.autoPinEdge(toSuperviewEdge:.bottom, withInset:ongoingBottomMargin)
ongoingCallView.autoPinWidthToSuperview(withMargin:ongoingHMargin)
ongoingCallView.setContentHuggingVerticalHigh()
// Incoming call controls
incomingCallView.autoPinEdge(toSuperviewEdge:.bottom, withInset:incomingBottomMargin)
incomingCallView.autoPinWidthToSuperview(withMargin:incomingHMargin)
incomingCallView.setContentHuggingVerticalHigh()
// Settings nag views
settingsNagView.autoPinEdge(toSuperviewEdge:.bottom, withInset:settingsNagBottomMargin)
settingsNagView.autoPinWidthToSuperview(withMargin:settingsNagHMargin)
settingsNagView.autoPinEdge(.top, to:.bottom, of:callStatusLabel)
}
updateRemoteVideoLayout()
updateLocalVideoLayout()
super.updateViewConstraints()
}
internal func updateRemoteVideoLayout() {
NSLayoutConstraint.deactivate(self.remoteVideoConstraints)
var constraints: [NSLayoutConstraint] = []
// We fill the screen with the remote video. The remote video's
// aspect ratio may not (and in fact will very rarely) match the
// aspect ratio of the current device, so parts of the remote
// video will be hidden offscreen.
//
// It's better to trim the remote video than to adopt a letterboxed
// layout.
if remoteVideoSize.width > 0 && remoteVideoSize.height > 0 &&
self.view.bounds.size.width > 0 && self.view.bounds.size.height > 0 {
var remoteVideoWidth = self.view.bounds.size.width
var remoteVideoHeight = self.view.bounds.size.height
if remoteVideoSize.width / self.view.bounds.size.width > remoteVideoSize.height / self.view.bounds.size.height {
remoteVideoWidth = round(self.view.bounds.size.height * remoteVideoSize.width / remoteVideoSize.height)
} else {
remoteVideoHeight = round(self.view.bounds.size.width * remoteVideoSize.height / remoteVideoSize.width)
}
constraints.append(remoteVideoView.autoSetDimension(.width, toSize:remoteVideoWidth))
constraints.append(remoteVideoView.autoSetDimension(.height, toSize:remoteVideoHeight))
constraints += remoteVideoView.autoCenterInSuperview()
remoteVideoView.frame = CGRect(origin:CGPoint.zero,
size:CGSize(width:remoteVideoWidth,
height:remoteVideoHeight))
remoteVideoView.isHidden = false
} else {
constraints += remoteVideoView.autoPinEdgesToSuperviewEdges()
remoteVideoView.isHidden = true
}
self.remoteVideoConstraints = constraints
// We need to force relayout to occur immediately (and not
// wait for a UIKit layout/render pass) or the remoteVideoView
// (which presumably is updating its CALayer directly) will
// ocassionally appear to have bad frames.
remoteVideoView.setNeedsLayout()
remoteVideoView.superview?.setNeedsLayout()
remoteVideoView.layoutIfNeeded()
remoteVideoView.superview?.layoutIfNeeded()
updateCallUI(callState: call.state)
}
internal func updateLocalVideoLayout() {
NSLayoutConstraint.deactivate(self.localVideoConstraints)
var constraints: [NSLayoutConstraint] = []
if localVideoView.isHidden {
let contactHMargin = CGFloat(30)
constraints.append(contactNameLabel.autoPinEdge(toSuperviewEdge:.right, withInset:contactHMargin))
constraints.append(callStatusLabel.autoPinEdge(toSuperviewEdge:.right, withInset:contactHMargin))
} else {
let spacing = CGFloat(10)
constraints.append(contactNameLabel.autoPinEdge(.right, to:.left, of:localVideoView, withOffset:-spacing))
constraints.append(callStatusLabel.autoPinEdge(.right, to:.left, of:localVideoView, withOffset:-spacing))
}
self.localVideoConstraints = constraints
updateCallUI(callState: call.state)
}
// MARK: - Methods
func showCallFailed(error: Error) {
// TODO Show something in UI.
Logger.error("\(TAG) call failed with error: \(error)")
}
// MARK: - View State
func localizedTextForCallState(_ callState: CallState) -> String {
assert(Thread.isMainThread)
switch callState {
case .idle, .remoteHangup, .localHangup:
return NSLocalizedString("IN_CALL_TERMINATED", comment: "Call setup status label")
case .dialing:
return NSLocalizedString("IN_CALL_CONNECTING", comment: "Call setup status label")
case .remoteRinging, .localRinging:
return NSLocalizedString("IN_CALL_RINGING", comment: "Call setup status label")
case .answering:
return NSLocalizedString("IN_CALL_SECURING", comment: "Call setup status label")
case .connected:
if let call = self.call {
let callDuration = call.connectionDuration()
let callDurationDate = Date(timeIntervalSinceReferenceDate:callDuration)
if dateFormatter == nil {
dateFormatter = DateFormatter()
dateFormatter!.dateFormat = "HH:mm:ss"
dateFormatter!.timeZone = TimeZone(identifier:"UTC")!
}
var formattedDate = dateFormatter!.string(from: callDurationDate)
if formattedDate.hasPrefix("00:") {
// Don't show the "hours" portion of the date format unless the
// call duration is at least 1 hour.
formattedDate = formattedDate.substring(from: formattedDate.index(formattedDate.startIndex, offsetBy: 3))
} else {
// If showing the "hours" portion of the date format, strip any leading
// zeroes.
if formattedDate.hasPrefix("0") {
formattedDate = formattedDate.substring(from: formattedDate.index(formattedDate.startIndex, offsetBy: 1))
}
}
return formattedDate
} else {
return NSLocalizedString("IN_CALL_TALKING", comment: "Call setup status label")
}
case .remoteBusy:
return NSLocalizedString("END_CALL_RESPONDER_IS_BUSY", comment: "Call setup status label")
case .localFailure:
if let error = call.error {
switch error {
case .timeout(description: _):
if self.call.direction == .outgoing {
return NSLocalizedString("CALL_SCREEN_STATUS_NO_ANSWER", comment: "Call setup status label after outgoing call times out")
}
default:
break
}
}
return NSLocalizedString("END_CALL_UNCATEGORIZED_FAILURE", comment: "Call setup status label")
}
}
func updateCallStatusLabel(callState: CallState) {
assert(Thread.isMainThread)
let text = String(format: CallStrings.callStatusFormat,
localizedTextForCallState(callState))
self.callStatusLabel.text = text
}
func updateCallUI(callState: CallState) {
assert(Thread.isMainThread)
updateCallStatusLabel(callState: callState)
if isShowingSettingsNag {
settingsNagView.isHidden = false
contactAvatarView.isHidden = true
ongoingCallView.isHidden = true
return
}
audioModeMuteButton.isSelected = call.isMuted
videoModeMuteButton.isSelected = call.isMuted
audioModeVideoButton.isSelected = call.hasLocalVideo
videoModeVideoButton.isSelected = call.hasLocalVideo
speakerPhoneButton.isSelected = call.isSpeakerphoneEnabled
// Show Incoming vs. Ongoing call controls
let isRinging = callState == .localRinging
incomingCallView.isHidden = !isRinging
incomingCallView.isUserInteractionEnabled = isRinging
ongoingCallView.isHidden = isRinging
ongoingCallView.isUserInteractionEnabled = !isRinging
// Rework control state if remote video is available.
let hasRemoteVideo = !remoteVideoView.isHidden
contactAvatarView.isHidden = hasRemoteVideo
// Rework control state if local video is available.
let hasLocalVideo = !localVideoView.isHidden
for subview in [speakerPhoneButton, audioModeMuteButton, audioModeVideoButton] {
subview?.isHidden = hasLocalVideo
}
for subview in [videoModeMuteButton, videoModeVideoButton] {
subview?.isHidden = !hasLocalVideo
}
// Also hide other controls if user has tapped to hide them.
if shouldRemoteVideoControlsBeHidden && !remoteVideoView.isHidden {
contactNameLabel.isHidden = true
callStatusLabel.isHidden = true
ongoingCallView.isHidden = true
} else {
contactNameLabel.isHidden = false
callStatusLabel.isHidden = false
}
// Dismiss Handling
switch callState {
case .remoteHangup, .remoteBusy, .localFailure:
Logger.debug("\(TAG) dismissing after delay because new state is \(callState)")
dismissIfPossible(shouldDelay:true)
case .localHangup:
Logger.debug("\(TAG) dismissing immediately from local hangup")
dismissIfPossible(shouldDelay:false)
default: break
}
if callState == .connected {
if callDurationTimer == nil {
let kDurationUpdateFrequencySeconds = 1 / 20.0
callDurationTimer = Timer.scheduledTimer(timeInterval: TimeInterval(kDurationUpdateFrequencySeconds),
target:self,
selector:#selector(updateCallDuration),
userInfo:nil,
repeats:true)
}
} else {
callDurationTimer?.invalidate()
callDurationTimer = nil
}
}
func updateCallDuration(timer: Timer?) {
updateCallStatusLabel(callState: call.state)
}
// MARK: - Actions
/**
* Ends a connected call. Do not confuse with `didPressDeclineCall`.
*/
func didPressHangup(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
if let call = self.call {
callUIAdapter.localHangupCall(call)
} else {
Logger.warn("\(TAG) hung up, but call was unexpectedly nil")
}
dismissIfPossible(shouldDelay:false)
}
func didPressMute(sender muteButton: UIButton) {
Logger.info("\(TAG) called \(#function)")
muteButton.isSelected = !muteButton.isSelected
if let call = self.call {
callUIAdapter.setIsMuted(call: call, isMuted: muteButton.isSelected)
} else {
Logger.warn("\(TAG) pressed mute, but call was unexpectedly nil")
}
}
func didPressSpeakerphone(sender speakerphoneButton: UIButton) {
Logger.info("\(TAG) called \(#function)")
speakerphoneButton.isSelected = !speakerphoneButton.isSelected
if let call = self.call {
callUIAdapter.setIsSpeakerphoneEnabled(call: call, isEnabled: speakerphoneButton.isSelected)
} else {
Logger.warn("\(TAG) pressed mute, but call was unexpectedly nil")
}
}
func didPressTextMessage(sender speakerphoneButton: UIButton) {
Logger.info("\(TAG) called \(#function)")
dismissIfPossible(shouldDelay:false)
}
func didPressAnswerCall(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
guard let call = self.call else {
Logger.error("\(TAG) call was unexpectedly nil. Terminating call.")
let text = String(format: CallStrings.callStatusFormat,
NSLocalizedString("END_CALL_UNCATEGORIZED_FAILURE", comment: "Call setup status label"))
self.callStatusLabel.text = text
dismissIfPossible(shouldDelay:true)
return
}
callUIAdapter.answerCall(call)
}
func didPressVideo(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
let hasLocalVideo = !sender.isSelected
if let call = self.call {
callUIAdapter.setHasLocalVideo(call: call, hasLocalVideo: hasLocalVideo)
} else {
Logger.warn("\(TAG) pressed video, but call was unexpectedly nil")
}
}
/**
* Denies an incoming not-yet-connected call, Do not confuse with `didPressHangup`.
*/
func didPressDeclineCall(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
if let call = self.call {
callUIAdapter.declineCall(call)
} else {
Logger.warn("\(TAG) denied call, but call was unexpectedly nil")
}
dismissIfPossible(shouldDelay:false)
}
func didPressShowCallSettings(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
markSettingsNagAsComplete()
dismissIfPossible(shouldDelay: false, ignoreNag: true, completion: {
// Find the frontmost presented UIViewController from which to present the
// settings views.
let fromViewController = UIApplication.shared.frontmostViewController
assert(fromViewController != nil)
// Construct the "settings" view & push the "privacy settings" view.
let navigationController = UIStoryboard.main.instantiateViewController(withIdentifier: "SettingsNavigationController") as! UINavigationController
assert(navigationController.viewControllers.count == 1)
let privacySettingsViewController = PrivacySettingsTableViewController()
navigationController.pushViewController(privacySettingsViewController, animated:false)
fromViewController?.present(navigationController, animated: true, completion: nil)
})
}
func didPressDismissNag(sender: UIButton) {
Logger.info("\(TAG) called \(#function)")
markSettingsNagAsComplete()
dismissIfPossible(shouldDelay: false, ignoreNag: true)
}
// We only show the "blocking" settings nag until the user has chosen
// to view the privacy settings _or_ dismissed the nag at least once.
//
// In either case, we set the "CallKit enabled" and "CallKit privacy enabled"
// settings to their default values to indicate that the user has reviewed
// them.
private func markSettingsNagAsComplete() {
Logger.info("\(TAG) called \(#function)")
let preferences = Environment.getCurrent().preferences!
preferences.setIsCallKitEnabled(preferences.isCallKitEnabled())
preferences.setIsCallKitPrivacyEnabled(preferences.isCallKitPrivacyEnabled())
}
// MARK: - CallObserver
internal func stateDidChange(call: SignalCall, state: CallState) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) new call status: \(state)")
self.updateCallUI(callState: state)
}
internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
self.updateCallUI(callState: call.state)
}
internal func muteDidChange(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
self.updateCallUI(callState: call.state)
}
internal func speakerphoneDidChange(call: SignalCall, isEnabled: Bool) {
AssertIsOnMainThread()
self.updateCallUI(callState: call.state)
}
// MARK: - Video
internal func updateLocalVideoTrack(localVideoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
guard self.localVideoTrack != localVideoTrack else {
return
}
self.localVideoTrack = localVideoTrack
var source: RTCAVFoundationVideoSource?
if localVideoTrack?.source is RTCAVFoundationVideoSource {
source = localVideoTrack?.source as! RTCAVFoundationVideoSource
}
localVideoView.captureSession = source?.captureSession
let isHidden = source == nil
Logger.info("\(TAG) \(#function) isHidden: \(isHidden)")
localVideoView.isHidden = isHidden
updateLocalVideoLayout()
}
internal func updateRemoteVideoTrack(remoteVideoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
guard self.remoteVideoTrack != remoteVideoTrack else {
return
}
self.remoteVideoTrack?.remove(remoteVideoView)
self.remoteVideoTrack = nil
remoteVideoView.renderFrame(nil)
self.remoteVideoTrack = remoteVideoTrack
self.remoteVideoTrack?.add(remoteVideoView)
shouldRemoteVideoControlsBeHidden = false
if remoteVideoTrack == nil {
remoteVideoSize = CGSize.zero
}
updateRemoteVideoLayout()
}
internal func dismissIfPossible(shouldDelay: Bool, ignoreNag: Bool = false, completion: (() -> Swift.Void)? = nil) {
if hasDismissed {
// Don't dismiss twice.
return
} else if !ignoreNag &&
call.direction == .incoming &&
UIDevice.current.supportsCallKit &&
(!Environment.getCurrent().preferences.isCallKitEnabled() ||
Environment.getCurrent().preferences.isCallKitPrivacyEnabled()) {
isShowingSettingsNag = true
// Update the nag view's copy to reflect the settings state.
if Environment.getCurrent().preferences.isCallKitEnabled() {
settingsNagDescriptionLabel.text = NSLocalizedString("CALL_VIEW_SETTINGS_NAG_DESCRIPTION_PRIVACY",
comment: "Reminder to the user of the benefits of disabling CallKit privacy.")
} else {
settingsNagDescriptionLabel.text = NSLocalizedString("CALL_VIEW_SETTINGS_NAG_DESCRIPTION_ALL",
comment: "Reminder to the user of the benefits of enabling CallKit and disabling CallKit privacy.")
}
settingsNagDescriptionLabel.superview?.setNeedsLayout()
if Environment.getCurrent().preferences.isCallKitEnabledSet() ||
Environment.getCurrent().preferences.isCallKitPrivacySet() {
// User has already touched these preferences, only show
// the "fleeting" nag, not the "blocking" nag.
// Show nag for N seconds.
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dismissIfPossible(shouldDelay: false, ignoreNag: true)
}
}
} else if shouldDelay {
hasDismissed = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.dismiss(animated: true, completion:completion)
}
} else {
hasDismissed = true
self.dismiss(animated: false, completion:completion)
}
}
// MARK: - CallServiceObserver
internal func didUpdateCall(call: SignalCall?) {
// Do nothing.
}
internal func didUpdateVideoTracks(localVideoTrack: RTCVideoTrack?,
remoteVideoTrack: RTCVideoTrack?) {
AssertIsOnMainThread()
updateLocalVideoTrack(localVideoTrack:localVideoTrack)
updateRemoteVideoTrack(remoteVideoTrack:remoteVideoTrack)
}
// MARK: - RTCEAGLVideoViewDelegate
internal func videoView(_ videoView: RTCEAGLVideoView, didChangeVideoSize size: CGSize) {
AssertIsOnMainThread()
if videoView != remoteVideoView {
return
}
Logger.info("\(TAG) \(#function): \(size)")
remoteVideoSize = size
updateRemoteVideoLayout()
}
}
|
gpl-3.0
|
e550cbfec1b27511313f9f50b3bee48f
| 39.981557 | 168 | 0.639707 | 5.370301 | false | false | false | false |
guidomb/PortalView
|
Sources/UIKit/PortalCarouselView.swift
|
1
|
4623
|
//
// PortalCarouselView.swift
// PortalView
//
// Created by Cristian Ames on 4/17/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
public final class PortalCarouselView<MessageType, CustomComponentRendererType: UIKitCustomComponentRenderer>: PortalCollectionView<MessageType, CustomComponentRendererType>
where CustomComponentRendererType.MessageType == MessageType {
public var isSnapToCellEnabled: Bool = false
fileprivate let onSelectionChange: (ZipListShiftOperation) -> MessageType?
fileprivate var lastOffset: CGFloat = 0
fileprivate var selectedIndex: Int = 0
public override init(items: [CollectionItemProperties<MessageType>], layoutEngine: LayoutEngine, layout: UICollectionViewLayout, rendererFactory: @escaping CustomComponentRendererFactory) {
onSelectionChange = { _ in .none }
super.init(
items: items,
layoutEngine: layoutEngine,
layout: layout,
rendererFactory: rendererFactory
)
}
public init(items: ZipList<CarouselItemProperties<MessageType>>?, layoutEngine: LayoutEngine, layout: UICollectionViewLayout, rendererFactory: @escaping CustomComponentRendererFactory, onSelectionChange: @escaping (ZipListShiftOperation) -> MessageType?) {
if let items = items {
let transform = { (item: CarouselItemProperties) -> CollectionItemProperties<MessageType> in
return collectionItem(
onTap: item.onTap,
identifier: item.identifier,
renderer: item.renderer)
}
selectedIndex = Int(items.centerIndex)
self.onSelectionChange = onSelectionChange
super.init(items: items.map(transform), layoutEngine: layoutEngine, layout: layout, rendererFactory: rendererFactory)
scrollToItem(self.selectedIndex, animated: false)
} else {
self.onSelectionChange = onSelectionChange
super.init(items: [], layoutEngine: layoutEngine, layout: layout, rendererFactory: rendererFactory)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
lastOffset = scrollView.contentOffset.x
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// At this moment we only support the message feature with the snap mode on.
// TODO: Add support for messaging regardless the snap mode.
// To do this feature we should detect the item selected not by adding or
// supressing one to the index but searching the active item in the screen
// at that moment. We could use `indexPathForItemAtPoint` for this purpose.
guard isSnapToCellEnabled else { return }
let currentOffset = CGFloat(scrollView.contentOffset.x)
if currentOffset == lastOffset {
return
}
let lastPosition = selectedIndex
if currentOffset > lastOffset {
if lastPosition < items.count - 1 {
selectedIndex = lastPosition + 1
scrollToItem(selectedIndex, animated: true) // Move to the right
onSelectionChange(.left(count: 1)) |> { mailbox.dispatch(message: $0) }
}
} else if currentOffset < lastOffset {
if lastPosition >= 1 {
selectedIndex = lastPosition - 1
scrollToItem(selectedIndex, animated: true) // Move to the left
onSelectionChange(.right(count: 1)) |> { mailbox.dispatch(message: $0) }
}
}
}
}
fileprivate extension PortalCarouselView {
fileprivate func scrollToItem(_ position: Int, animated: Bool) {
DispatchQueue.main.async {
let indexPath = IndexPath(item: position, section: 0)
self.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated)
}
}
fileprivate func shiftDirection(actual: Int, old: Int) -> ZipListShiftOperation? {
if actual < old {
return ZipListShiftOperation.left(count: UInt(old - actual))
} else if actual > old {
return ZipListShiftOperation.right(count: UInt(actual - old))
} else {
return .none
}
}
}
|
mit
|
ce64d6ca8c27017a6c5e70db05e64b50
| 41.40367 | 260 | 0.642579 | 5.522103 | false | false | false | false |
darrarski/DRNet
|
DRNet-Example-iOS/DRNet-Example-iOS/UI/Views/MenuItemCell.swift
|
1
|
2042
|
//
// MenuItemCell.swift
// DRNet-Example-iOS
//
// Created by Dariusz Rybicki on 10/11/14.
// Copyright (c) 2014 Darrarski. All rights reserved.
//
import UIKit
class MenuItemCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
private let borderColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
private let alternativeColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
override func awakeFromNib() {
super.awakeFromNib()
cleanUp()
let borderView = UIView()
borderView.setTranslatesAutoresizingMaskIntoConstraints(false)
borderView.backgroundColor = borderColor
addSubview(borderView)
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[border]|",
options: .allZeros,
metrics: nil,
views: [
"border": borderView
]
)
)
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:[border(size)]|",
options: .allZeros,
metrics: [
"size": 0.5
],
views: [
"border": borderView
]
)
)
}
override func prepareForReuse() {
super.prepareForReuse()
cleanUp()
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
UIView.animateWithDuration({ animated ? 0.5 : 0 }(), animations: { () -> Void in
self.backgroundColor = highlighted ? self.alternativeColor : UIColor.clearColor()
})
}
override func setSelected(selected: Bool, animated: Bool) {
setHighlighted(selected, animated: animated)
}
private func cleanUp() {
titleLabel.text = nil
subtitleLabel.text = nil
}
}
|
mit
|
db63f56f581b5008f3fc8814c883df17
| 25.881579 | 93 | 0.553869 | 5.548913 | false | false | false | false |
duke-compsci408-fall2014/Pawns
|
BayAreaChess/BayAreaChess/Login.swift
|
1
|
4499
|
//
// Login.swift
// BayAreaChess
//
// Created by Carlos Reyes on 9/18/14.
// Copyright (c) 2014 Bay Area Chess. All rights reserved.
//
import UIKit
class Login: UIViewController, UITextFieldDelegate {
@IBOutlet var username : UITextField!;
@IBOutlet var password : UITextField!;
@IBOutlet var label : UILabel!;
@IBOutlet var name : UILabel?;
@IBOutlet var descriptions : UITextView?;
@IBOutlet var dates : UILabel?;
@IBOutlet var cost : UILabel?;
var currentURL : String = "";
var myID : Int? = 0;
override func viewDidLoad() {
super.viewDidLoad();
self.username.delegate = self;
self.password.delegate = self;
username.attributedPlaceholder = NSAttributedString(string:Constants.Label.user,
attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]);
password.attributedPlaceholder = NSAttributedString(string:Constants.Label.pass,
attributes:[NSForegroundColorAttributeName: UIColor.lightTextColor()]);
}
/**
* Validates the login information of a user. Also makes sure that user does not
* enter nil values.
*
* @param sender The sending class
*/
@IBAction func verifyLogin (sender : AnyObject) {
if (username.text != "" && password.text != "") {
currentURL = Constants.Base.verifyURL + username.text + "/" + password.text;
self.connect("");
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
var data = NSMutableData();
func connect(query:NSString) {
var url = NSURL(string: currentURL);
var request = NSURLRequest(URL: url!);
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true);
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println(Constants.Response.recieved);
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data = NSMutableData(); // Flush data pipe
self.data.appendData(conData);
}
/**
* If there is a successful server response, will attempt to log in
*
* @param connection The connection from which the class recieves the response
*/
func connectionDidFinishLoading(connection: NSURLConnection!) {
var data : NSData = NSData();
data = self.data;
println(data);
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary;
var verification = getFromJSON (json, field: Constants.JSON.verification);
println(Constants.JSON.failure);
if (verification == Constants.JSON.success) {
label.text = "";
self.performSegueWithIdentifier(Constants.Base.login, sender: self);
}
else {
label.textColor = UIColor.redColor();
label.text = Constants.Label.rejected;
}
}
deinit {
println(Constants.Response.deiniting);
}
/**
* Safely returns field value from JSON
*
* @param input The JSON object, of type NSDictionary
* @param field The key to be used to retrieve a field
* @return The value associated with the key, returns empty string if not found
*/
func getFromJSON (input : NSDictionary, field : String) -> String {
var tournamentData : String! = "";
if ((input[field] as? String) != nil) {
tournamentData = input[Constants.JSON.verification] as String;
}
return tournamentData;
}
/**
* Opening sidebar triggered by an event
*/
@IBAction func onMenu() {
(tabBarController as TabBarController).sidebar.showInViewController(self, animated: true)
}
/**
* Passes the username from the login page to the user's dashboard
*
* @param segue The UIStoryboardSegue
* @param sender The sending class
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == Constants.Base.login) {
let vc = segue.destinationViewController as User;
vc.myUsername = self.username.text as String;
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
|
mit
|
d47c2814b880801252d5d1c46e6a5efb
| 31.846715 | 106 | 0.630585 | 4.922319 | false | false | false | false |
brave/browser-ios
|
Utils/MenuHelper.swift
|
2
|
2251
|
/* 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
@objc public protocol MenuHelperInterface {
@objc optional func menuHelperCopy(_ sender: Notification)
@objc optional func menuHelperOpenAndFill(_ sender: Notification)
@objc optional func menuHelperReveal(_ sender: Notification)
@objc optional func menuHelperSecure(_ sender: Notification)
@objc optional func menuHelperFindInPage(_ sender: Notification)
}
open class MenuHelper: NSObject {
open static let SelectorCopy: Selector = #selector(MenuHelperInterface.menuHelperCopy(_:))
open static let SelectorHide: Selector = #selector(MenuHelperInterface.menuHelperSecure(_:))
open static let SelectorOpenAndFill: Selector = #selector(MenuHelperInterface.menuHelperOpenAndFill(_:))
open static let SelectorReveal: Selector = #selector(MenuHelperInterface.menuHelperReveal(_:))
open static let SelectorFindInPage: Selector = #selector(MenuHelperInterface.menuHelperFindInPage(_:))
open class var defaultHelper: MenuHelper {
struct Singleton {
static let instance = MenuHelper()
}
return Singleton.instance
}
open func setItems() {
let revealPasswordTitle = Strings.RevealPassword
let revealPasswordItem = UIMenuItem(title: revealPasswordTitle, action: MenuHelper.SelectorReveal)
let hidePasswordTitle = Strings.HidePassword
let hidePasswordItem = UIMenuItem(title: hidePasswordTitle, action: MenuHelper.SelectorHide)
let copyTitle = Strings.Copy
let copyItem = UIMenuItem(title: copyTitle, action: MenuHelper.SelectorCopy)
let openAndFillTitle = Strings.Open_and_Fill
let openAndFillItem = UIMenuItem(title: openAndFillTitle, action: MenuHelper.SelectorOpenAndFill)
let findInPageTitle = Strings.Find_in_Page
let findInPageItem = UIMenuItem(title: findInPageTitle, action: MenuHelper.SelectorFindInPage)
UIMenuController.shared.menuItems = [copyItem, revealPasswordItem, hidePasswordItem, openAndFillItem, findInPageItem]
}
}
|
mpl-2.0
|
d9a1fdcb86f2ee5c37c1ecd58dcf7ba9
| 45.895833 | 125 | 0.747668 | 5.127563 | false | false | false | false |
S7Vyto/TouchVK
|
TouchVK/TouchVK/Models/News/NewsModel.swift
|
1
|
2019
|
//
// NewsModel.swift
// TouchVK
//
// Created by Sam on 08/02/2017.
// Copyright © 2017 Semyon Vyatkin. All rights reserved.
//
import Foundation
import RxSwift
import RxRealm
import RealmSwift
class NewsModel {
private let disposeBag = DisposeBag()
private let netService = NetworkService(url: URL(string: URLConst.baseUrl)!)
private let dbService = try! Realm()
var news = Variable<[News]>([])
func fetchData() {
let inputObservable = netService.responseObjects(for: VKApi.news)
.catchError({ (error) -> Observable<[News]> in
return Observable.just([])
})
.retry(3)
.shareReplay(1)
inputObservable
.subscribe(onNext: { [weak weakSelf = self] news in
guard !news.isEmpty else {
return
}
if let data = weakSelf?.dbService.objects(News.self) {
try! weakSelf?.dbService.write {
weakSelf?.dbService.delete(data)
}
}
try! weakSelf?.dbService.write {
weakSelf?.dbService.add(news)
}
})
.addDisposableTo(disposeBag)
inputObservable
.subscribe(onNext: { [weak weakSelf = self] _ in
let resultBag = DisposeBag()
guard let data = weakSelf?.dbService.objects(News.self).sorted(byKeyPath: "date",
ascending: false) else {
return
}
Observable.arrayWithChangeset(from: data)
.subscribe(onNext: { (news, changes) in
weakSelf?.news.value = news
})
.addDisposableTo(resultBag)
})
.addDisposableTo(disposeBag)
}
}
|
apache-2.0
|
f5c52ec3d26dd5895c2ca380edbb0b74
| 31.031746 | 103 | 0.479683 | 5.324538 | false | false | false | false |
seivan/VectorArithmetic
|
Source/Shared/VectorArithmetic.swift
|
1
|
12027
|
import CoreGraphics
public protocol VectorOperatable {
init(horizontal:Double,vertical:Double)
var horizontal:Double { get set }
var vertical:Double { get set }
}
public protocol VectorArithmetic : VectorOperatable {
var angleInRadians:Double {get}
var magnitude:Double {get}
var length:Double {get}
var lengthSquared:Double {get}
func dotProduct <T : VectorArithmetic>(vector:T) -> Double
func crossProduct <T : VectorArithmetic>(vector:T) -> Double
func distanceTo <T : VectorArithmetic>(vector:T) -> Double
var reversed:Self {get}
var normalized:Self {get}
func limited(scalar:Double) -> Self
func scaled(scalar:Double) -> Self
func angled(scalar:Double) -> Self
}
//Since these structs already have != operator for themselves, but not against each we can't use a generic constraint
public func != (lhs: CGVector , rhs: CGSize) -> Bool {
return (lhs == rhs) == false
}
public func != (lhs: CGVector , rhs: CGPoint) -> Bool {
return (lhs == rhs) == false
}
public func != (lhs: CGSize , rhs: CGVector) -> Bool {
return (lhs == rhs) == false
}
public func != (lhs: CGSize , rhs: CGPoint) -> Bool {
return (lhs == rhs) == false
}
public func != (lhs: CGPoint , rhs: CGVector) -> Bool {
return (lhs == rhs) == false
}
public func != (lhs: CGPoint , rhs: CGSize) -> Bool {
return (lhs == rhs) == false
}
public func == <T:VectorOperatable, U:VectorOperatable> (lhs:T,rhs:U) -> Bool {
return (lhs.horizontal == rhs.horizontal && lhs.vertical == rhs.vertical)
}
//Gives ambigious operator since the struct already does compare to its own type
//func != <T:VectorOperatable, U:VectorOperatable>(lhs: T , rhs: U) -> Bool {
// return (lhs == rhs) == false
//}
public func <= <T:VectorOperatable, U:VectorOperatable>(lhs:T, rhs:U) -> Bool {
return (lhs < rhs) || (lhs == rhs)
}
public func < <T:VectorOperatable, U:VectorOperatable>(lhs: T , rhs: U) -> Bool {
return (lhs.horizontal < rhs.horizontal || lhs.vertical < rhs.vertical)
}
public func >= <T:VectorOperatable, U:VectorOperatable>(lhs: T , rhs: U) -> Bool {
return (lhs > rhs) || ( lhs == rhs)
}
public func > <T:VectorOperatable, U:VectorOperatable>(lhs: T , rhs: U) -> Bool {
return (lhs <= rhs) == false
}
public func - <T:VectorOperatable, U:VectorOperatable>(lhs: T, rhs:U) -> T {
return T(horizontal: lhs.horizontal-rhs.horizontal, vertical: lhs.vertical-rhs.vertical)
}
public func -= <T:VectorOperatable, U:VectorOperatable>(inout lhs: T, rhs:U) {
lhs = lhs - rhs
}
public func + <T:VectorOperatable, U:VectorOperatable>(lhs: T, rhs:U) -> T {
return T(horizontal: lhs.horizontal+rhs.horizontal, vertical: lhs.vertical+rhs.vertical)
}
public func += <T:VectorOperatable, U:VectorOperatable>(inout lhs: T, rhs:U) {
lhs = lhs + rhs
}
public func * <T:VectorOperatable, U:VectorOperatable>(lhs: T, rhs:U) -> T {
return T(horizontal: lhs.horizontal*rhs.horizontal, vertical: lhs.vertical*rhs.vertical);
}
public func *= <T:VectorOperatable, U:VectorOperatable>(inout lhs: T, rhs:U) {
lhs = lhs * rhs
}
public func / <T:VectorOperatable, U:VectorOperatable>(lhs:T, rhs:U) -> T {
return T(horizontal: lhs.horizontal/rhs.horizontal, vertical: lhs.vertical/rhs.vertical);
}
public func /= <T:VectorOperatable, U:VectorOperatable>(inout lhs:T, rhs:U) -> T {
lhs = lhs / rhs
return lhs
}
public func / <T:VectorOperatable>(lhs:T, scalar:Double) -> T {
return T(horizontal: lhs.horizontal/scalar, vertical: lhs.vertical/scalar);
}
public func /= <T:VectorOperatable>(inout lhs:T, scalar:Double) -> T {
lhs = lhs / scalar
return lhs
}
public func * <T:VectorOperatable>(lhs: T, scalar:Double) -> T {
return T(horizontal: lhs.horizontal*scalar, vertical: lhs.vertical*scalar)
}
func * <T:VectorOperatable>(scalar:Double, rhs: T) -> T {
return T(horizontal: rhs.horizontal*scalar, vertical: rhs.vertical*scalar)
}
func *= <T:VectorOperatable>(inout lhs: T, value:Double) {
lhs = lhs * value
}
internal struct InternalVectorArithmetic {
internal static func angleInRadians <T : VectorArithmetic>(vector:T) -> Double {
let normalizedVector = self.normalized(vector)
let theta = atan2(normalizedVector.vertical, normalizedVector.horizontal)
return theta + M_PI_2 * -1
}
internal static func magnitude <T : VectorArithmetic>(vector:T) -> Double {
return sqrt(self.lengthSquared(vector))
}
internal static func lengthSquared <T : VectorArithmetic>(vector:T) -> Double {
return ((vector.horizontal*vector.horizontal) + (vector.vertical*vector.vertical))
}
internal static func reversed <T : VectorArithmetic>(vector:T) -> T {
return vector * -1
}
internal static func dotProduct <T : VectorOperatable, U : VectorOperatable > (vector:T, otherVector:U) -> Double {
return (vector.horizontal*otherVector.horizontal) + (vector.vertical*otherVector.vertical)
}
internal static func crossProduct <T : VectorArithmetic, U : VectorArithmetic > (vector:T, otherVector:U) -> Double {
let deltaAngle = sin(self.angleInRadians(vector) - self.angleInRadians(otherVector))
return self.magnitude(vector) * self.magnitude(otherVector) * deltaAngle
}
internal static func distanceTo <T : VectorArithmetic, U : VectorArithmetic > (vector:T, otherVector:U) -> Double {
let deltaX = Double.abs(vector.horizontal - otherVector.horizontal)
let deltaY = Double.abs(vector.vertical - otherVector.vertical)
return self.magnitude(T(horizontal: deltaX, vertical: deltaY))
}
internal static func normalized <T : VectorArithmetic>(vector:T) -> T {
let length = self.magnitude(vector)
var newPoint:T = vector
if(length > 0.0) {
newPoint /= length
}
return newPoint
}
internal static func limit <T : VectorArithmetic>(vector:T, scalar:Double) -> T {
var newPoint = vector
if(self.magnitude(vector) > scalar) {
newPoint = self.normalized(newPoint) * scalar
}
return newPoint
}
internal static func vectorWithAngle <T:VectorArithmetic>(vector:T, scalar:Double) -> T {
let length = self.magnitude(vector)
return T(horizontal: cos(scalar) * length, vertical: sin(scalar) * length)
}
}
extension CGPoint: VectorArithmetic {
public init(horizontal:Double,vertical:Double) {
self.init(x: horizontal, y: vertical)
}
// public init(x:Double, y:Double) {
// self.init(x:CGFloat(x), y:CGFloat(y))
// }
public var horizontal:Double {
get { return Double(self.x) }
set { self.x = CGFloat(newValue) }
}
public var vertical:Double {
get {return Double(self.y) }
set {self.y = CGFloat(newValue) }
}
public var angleInRadians:Double { return InternalVectorArithmetic.angleInRadians(self)}
public var magnitude:Double { return InternalVectorArithmetic.magnitude(self) }
public var length:Double { return self.magnitude }
public var lengthSquared:Double { return InternalVectorArithmetic.lengthSquared(self) }
public func dotProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.dotProduct(self, otherVector: vector) }
public func crossProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.crossProduct(self, otherVector: vector) }
public func distanceTo <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.distanceTo(self, otherVector: vector) }
public var reversed:CGPoint { return InternalVectorArithmetic.reversed(self) }
public var normalized:CGPoint { return InternalVectorArithmetic.normalized(self) }
public func limited(scalar:Double) -> CGPoint { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func scaled(scalar:Double) -> CGPoint { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func angled(scalar:Double) -> CGPoint { return InternalVectorArithmetic.vectorWithAngle(self, scalar: scalar) }
}
extension CGSize: VectorArithmetic {
public init(horizontal:Double,vertical:Double) {
self.init(width: horizontal, height: vertical)
}
// public init(width:Double, height:Double) {
// self.init(width:CGFloat(width), height:CGFloat(height))
// }
public var horizontal:Double {
get { return Double(self.width) }
set { self.width = CGFloat(newValue) }
}
public var vertical:Double {
get {return Double(self.height) }
set {self.height = CGFloat(newValue) }
}
public var angleInRadians:Double { return InternalVectorArithmetic.angleInRadians(self) }
public var magnitude:Double { return InternalVectorArithmetic.magnitude(self) }
public var length:Double { return self.magnitude }
public var lengthSquared:Double { return InternalVectorArithmetic.lengthSquared(self) }
public func dotProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.dotProduct(self, otherVector: vector) }
public func crossProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.crossProduct(self, otherVector: vector) }
public func distanceTo <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.distanceTo(self, otherVector: vector) }
public var reversed:CGSize { return InternalVectorArithmetic.reversed(self) }
public var normalized:CGSize { return InternalVectorArithmetic.normalized(self) }
public func limited(scalar:Double) -> CGSize { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func scaled(scalar:Double) -> CGSize { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func angled(scalar:Double) -> CGSize { return InternalVectorArithmetic.vectorWithAngle(self, scalar: scalar) }
}
extension CGVector: VectorArithmetic {
public init(horizontal:Double,vertical:Double) {
self.dx = CGFloat(horizontal)
self.dy = CGFloat(vertical)
}
public init(_ dx:Double, _ dy:Double) {
self.dx = CGFloat(dx)
self.dy = CGFloat(dy)
}
public var horizontal:Double {
get { return Double(self.dx) }
set { self.dx = CGFloat(newValue) }
}
public var vertical:Double {
get {return Double(self.dy) }
set {self.dy = CGFloat(newValue) }
}
public var angleInRadians:Double { return InternalVectorArithmetic.angleInRadians(self) }
public var magnitude:Double { return InternalVectorArithmetic.magnitude(self) }
public var length:Double { return self.magnitude }
public var lengthSquared:Double { return InternalVectorArithmetic.lengthSquared(self) }
public func dotProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.dotProduct(self, otherVector: vector) }
public func crossProduct <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.crossProduct(self, otherVector: vector) }
public func distanceTo <T : VectorArithmetic> (vector:T) -> Double { return InternalVectorArithmetic.distanceTo(self, otherVector: vector) }
public var reversed:CGVector { return InternalVectorArithmetic.reversed(self) }
public var normalized:CGVector { return InternalVectorArithmetic.normalized(self) }
public func limited(scalar:Double) -> CGVector { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func scaled(scalar:Double) -> CGVector { return InternalVectorArithmetic.limit(self, scalar: scalar) }
public func angled(scalar:Double) -> CGVector { return InternalVectorArithmetic.vectorWithAngle(self, scalar: scalar) }
}
extension VectorOperatable {
public var point: CGPoint {
return CGPoint(x: horizontal, y: vertical)
}
public var size: CGSize {
return CGSize(width: horizontal, height: vertical)
}
public var vector: CGVector {
return CGVector(dx: horizontal, dy: vertical)
}
}
extension CGRect {
public var widthVector: CGVector {
return CGVector(dx: size.width, dy: 0)
}
public var heightVector: CGVector {
return CGVector(dx: 0, dy: size.height)
}
}
|
mit
|
76976cd48a72669de5780fd7927e82cc
| 36.5875 | 146 | 0.708988 | 3.761964 | false | false | false | false |
zach-unbounded/MineSweeper
|
MineSweeper/MSSoundSystem.swift
|
1
|
3180
|
//
// MSSoundSystem.swift
// MineSweeper
//
// Created by Zachary Burgess on 01/12/2015.
// Copyright © 2015 V.Rei Ltd. All rights reserved.
//
import Foundation
import AVFoundation
class MSSoundSystem {
static let sharedInstance = MSSoundSystem()
let backgroundMusicFileURL:NSURL = NSBundle.mainBundle().URLForResource("backgroundMusic", withExtension: "mp3")!
var soundSession:AVAudioSession = AVAudioSession.sharedInstance()
var audioEngine: AVAudioEngine = AVAudioEngine()
var backgroundMusicFilePlayer: AVAudioPlayerNode
init() {
// init the sound session
do{
try soundSession.setCategory(AVAudioSessionCategoryAmbient)
}
catch {
NSLog("Problem setting up ambient categry")
}
backgroundMusicFilePlayer = AVAudioPlayerNode()
self.setupBackgroundMusic()
}
func setupBackgroundMusic() {
var audioFile : AVAudioFile
do {
print("Background Music file location: \(backgroundMusicFileURL.absoluteString)")
audioFile = try AVAudioFile(forReading: backgroundMusicFileURL)
let audioFormat = audioFile.processingFormat
let audioFrameCount = UInt32(audioFile.length)
let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)
do {
try audioFile.readIntoBuffer(audioFileBuffer, frameCount:audioFrameCount)
let mainMixer = audioEngine.mainMixerNode
audioEngine.attachNode(backgroundMusicFilePlayer)
audioEngine.connect(backgroundMusicFilePlayer, to:mainMixer, format:audioFileBuffer.format)
do {
try audioEngine.start()
// setting volume to half. and pause the music until we are ready to play!
backgroundMusicFilePlayer.volume = 0.5
backgroundMusicFilePlayer.pause()
backgroundMusicFilePlayer.scheduleBuffer(audioFileBuffer, atTime: nil, options:.Loops, completionHandler: nil)
} catch {
print("Failed to start engine!");
}
} catch {
print("Failed to read into buffer!");
}
}
catch {
print("Background music failed to load!");
}
}
func setVolumeForBackgroundMusic(newVolume : Float) {
backgroundMusicFilePlayer.volume = newVolume
}
func stopBackgroundMusic() {
if backgroundMusicFilePlayer.playing {
backgroundMusicFilePlayer.stop()
}
}
func switchBackgroundPause() {
if backgroundMusicFilePlayer.playing {
backgroundMusicFilePlayer.pause()
}
else {
backgroundMusicFilePlayer.play()
}
}
func playBackgroundMusic() {
if !backgroundMusicFilePlayer.playing {
backgroundMusicFilePlayer.play()
}
}
func shutdown() {
backgroundMusicFilePlayer.stop()
}
}
|
gpl-3.0
|
02402d1dd8b3c2485b8b7fb43d904eec
| 32.114583 | 130 | 0.605222 | 5.616608 | false | false | false | false |
ypopovych/Boilerplate
|
Sources/Boilerplate/InvalidationToken.swift
|
2
|
4016
|
//===--- InvalidationToken.swift -------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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.
//===----------------------------------------------------------------------===//
public class InvalidationToken {
//TODO: change to atomics
private var _valid:Bool
public init(valid:Bool = true) {
self._valid = valid
}
public var valid:Bool {
get {
return _valid
}
set {
_valid = newValue
}
}
}
public extension InvalidationToken {
public func closure(_ f:@escaping ()->Void) -> ()->Void {
return {
if self.valid {
f()
}
}
}
public func closure<A>(_ f:@escaping (A)->Void) -> (A)->Void {
return { a in
if self.valid {
f(a)
}
}
}
public func closure<A, B>(_ f:@escaping (A, B)->Void) -> (A, B)->Void {
return { a, b in
if self.valid {
f(a, b)
}
}
}
public func closure<A, B, C>(_ f:@escaping (A, B, C)->Void) -> (A, B, C)->Void {
return { a, b, c in
if self.valid {
f(a, b, c)
}
}
}
public func closure<A, B, C, D>(_ f:@escaping (A, B, C, D)->Void) -> (A, B, C, D)->Void {
return { a, b, c, d in
if self.valid {
f(a, b, c, d)
}
}
}
public func closure<A, B, C, D, E>(_ f:@escaping (A, B, C, D, E)->Void) -> (A, B, C, D, E)->Void {
return { a, b, c, d, e in
if self.valid {
f(a, b, c, d, e)
}
}
}
public func closure<A, B, C, D, E, F>(_ fun:@escaping (A, B, C, D, E, F)->Void) -> (A, B, C, D, E, F)->Void {
return { a, b, c, d, e, f in
if self.valid {
fun(a, b, c, d, e, f)
}
}
}
public func closure<A, B, C, D, E, F, G>(_ fun:@escaping (A, B, C, D, E, F, G)->Void) -> (A, B, C, D, E, F, G)->Void {
return { a, b, c, d, e, f, g in
if self.valid {
fun(a, b, c, d, e, f, g)
}
}
}
public func closure<A, B, C, D, E, F, G, H>(_ fun:@escaping (A, B, C, D, E, F, G, H)->Void) -> (A, B, C, D, E, F, G, H)->Void {
return { a, b, c, d, e, f, g, h in
if self.valid {
fun(a, b, c, d, e, f, g, h)
}
}
}
public func closure<A, B, C, D, E, F, G, H, I>(_ fun:@escaping (A, B, C, D, E, F, G, H, I)->Void) -> (A, B, C, D, E, F, G, H, I)->Void {
return { a, b, c, d, e, f, g, h, i in
if self.valid {
fun(a, b, c, d, e, f, g, h, i)
}
}
}
public func closure<A, B, C, D, E, F, G, H, I, J>(_ fun:@escaping (A, B, C, D, E, F, G, H, I, J)->Void) -> (A, B, C, D, E, F, G, H, I, J)->Void {
return { a, b, c, d, e, f, g, h, i, j in
if self.valid {
fun(a, b, c, d, e, f, g, h, i, j)
}
}
}
public func closure<A, B, C, D, E, F, G, H, I, J, K>(_ fun:@escaping (A, B, C, D, E, F, G, H, I, J, K)->Void) -> (A, B, C, D, E, F, G, H, I, J, K)->Void {
return { a, b, c, d, e, f, g, h, i, j, k in
if self.valid {
fun(a, b, c, d, e, f, g, h, i, j, k)
}
}
}
}
|
apache-2.0
|
8ed88869730cdc37195dbdd3b1ac2e1b
| 29.656489 | 158 | 0.412102 | 3.127726 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Edit data/Offline edit and sync/OfflineEditingViewController.swift
|
1
|
20786
|
//
// Copyright 2016 Esri.
//
// 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 ArcGIS
class OfflineEditingViewController: UIViewController {
@IBOutlet var mapView: AGSMapView!
@IBOutlet var extentView: UIView!
@IBOutlet var sketchToolbar: UIToolbar!
@IBOutlet var serviceModeToolbar: UIToolbar!
@IBOutlet var geodatabaseModeToolbar: UIToolbar!
@IBOutlet var doneBBI: UIBarButtonItem!
@IBOutlet var barButtonItem: UIBarButtonItem!
@IBOutlet var syncBBI: UIBarButtonItem!
@IBOutlet var instructionsLabel: UILabel!
private var sketchEditor: AGSSketchEditor?
private let featureServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer")!
private var featureTable: AGSServiceFeatureTable?
private var syncTask: AGSGeodatabaseSyncTask?
private var generatedGeodatabase: AGSGeodatabase?
private var generateJob: AGSGenerateGeodatabaseJob?
private var syncJob: AGSSyncGeodatabaseJob?
private var popupsViewController: AGSPopupsViewController?
private var liveMode = true {
didSet {
updateUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["OfflineEditingViewController", "FeatureLayersViewController"]
// Use the San Francisco tile package as the basemap.
let tileCache = AGSTileCache(name: "SanFrancisco")
let localTiledLayer = AGSArcGISTiledLayer(tileCache: tileCache)
let map = AGSMap(basemap: AGSBasemap(baseLayer: localTiledLayer))
// Setup extent view.
extentView.layer.borderColor = UIColor.red.cgColor
extentView.layer.borderWidth = 3
mapView.map = map
mapView.touchDelegate = self
// Initialize the sketch editor and assign it to the map view.
sketchEditor = AGSSketchEditor()
mapView.sketchEditor = sketchEditor
// Initialize sync task.
syncTask = AGSGeodatabaseSyncTask(url: featureServiceURL)
// Add online feature layers.
addFeatureLayers()
}
// MARK: - Helper methods
private func addFeatureLayers() {
// Iterate through the layers in the service.
syncTask?.load { [weak self] (error) in
if let error = error {
print("Could not load feature service \(error)")
} else {
guard let self = self else {
return
}
if let featureServiceInfo = self.syncTask?.featureServiceInfo,
let map = self.mapView.map {
for index in featureServiceInfo.layerInfos.indices.reversed() {
let layerInfo = featureServiceInfo.layerInfos[index]
// For each layer in the serice, add a layer to the map.
let layerURL = self.featureServiceURL.appendingPathComponent(String(index))
let featureTable = AGSServiceFeatureTable(url: layerURL)
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
featureLayer.name = layerInfo.name
map.operationalLayers.add(featureLayer)
}
}
// Enable the generate geodatabase bar button item.
self.barButtonItem.isEnabled = true
}
}
}
private func frameToExtent() -> AGSEnvelope {
let frame = mapView.convert(extentView.frame, from: view)
let minPoint = mapView.screen(toLocation: frame.origin)
let maxPoint = mapView.screen(toLocation: CGPoint(x: frame.origin.x + frame.width, y: frame.origin.y + frame.height))
let extent = AGSEnvelope(min: minPoint, max: maxPoint)
return extent
}
private func updateUI() {
if liveMode {
serviceModeToolbar.isHidden = false
instructionsLabel.isHidden = true
barButtonItem.title = "Generate Geodatabase"
} else {
serviceModeToolbar.isHidden = true
updateLabelWithEdits()
}
}
private func updateLabelWithEdits() {
let dispatchGroup = DispatchGroup()
var totalCount = 0
for featureTable in generatedGeodatabase!.geodatabaseFeatureTables where featureTable.loadStatus == .loaded {
dispatchGroup.enter()
featureTable.addedFeaturesCount { (count, _) in
totalCount += count
dispatchGroup.leave()
}
dispatchGroup.enter()
featureTable.updatedFeaturesCount { (count, _) in
totalCount += count
dispatchGroup.leave()
}
dispatchGroup.enter()
featureTable.deletedFeaturesCount { (count, _) in
totalCount += count
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) { [weak self] in
self?.instructionsLabel?.text = "Data from geodatabase: \(totalCount) edits"
}
}
private func switchToServiceMode() {
// Hide the extent view.
extentView.isHidden = true
// Re-enable interactions.
mapView.interactionOptions.isPanEnabled = true
mapView.interactionOptions.isZoomEnabled = true
mapView.interactionOptions.isRotateEnabled = true
if let generatedGeodatabase = generatedGeodatabase {
// Unregister the geodatabase.
syncTask?.unregisterGeodatabase(generatedGeodatabase) { (error: Error?) in
if let error = error {
print("Error while unregistering geodatabase: \(error.localizedDescription)")
}
}
}
// Remove all layers added from the geodatabase.
mapView.map?.operationalLayers.removeAllObjects()
// Add layers from the service.
addFeatureLayers()
// Update the flag.
liveMode = true
generatedGeodatabase = nil
// Delete exisiting geodatabases.
deleteAllGeodatabases()
}
private func deleteAllGeodatabases() {
// Remove all files with .geodatabase, .geodatabase-shm and .geodatabase-wal file extensions.
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let files = try FileManager.default.contentsOfDirectory(atPath: documentDirectoryURL.path)
for file in files {
let remove = file.hasSuffix(".geodatabase") || file.hasSuffix(".geodatabase-shm") || file.hasSuffix(".geodatabase-wal")
if remove {
let url = documentDirectoryURL.appendingPathComponent(file)
try FileManager.default.removeItem(at: url)
}
}
print("Deleted all local data")
} catch {
print(error)
}
}
@objc
func sketchChanged(_ notification: Notification) {
// Check if the sketch geometry is valid to decide whether or not to enable the "Done" button.
if let geometry = self.mapView.sketchEditor?.geometry, !geometry.isEmpty {
doneBBI.isEnabled = true
}
}
private func disableSketchEditor() {
mapView.sketchEditor?.stop()
mapView.sketchEditor?.clearGeometry()
sketchToolbar.isHidden = true
}
private func displayLayersFromGeodatabase() {
guard let generatedGeodatabase = generatedGeodatabase else {
return
}
generatedGeodatabase.load { [weak self] (error) in
guard let self = self else {
return
}
if let error = error {
print(error)
} else {
self.liveMode = false
self.mapView.map?.operationalLayers.removeAllObjects()
AGSLoadObjects(generatedGeodatabase.geodatabaseFeatureTables) { (success) in
if success {
for featureTable in generatedGeodatabase.geodatabaseFeatureTables.reversed() {
// Check if feature table has geometry.
if featureTable.hasGeometry {
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
self.mapView.map?.operationalLayers.add(featureLayer)
}
}
self.presentAlert(message: "Now showing layers from the geodatabase")
// Ensure that the user does not move outside of the downloaded extent view.
self.mapView.interactionOptions.isPanEnabled = false
self.mapView.interactionOptions.isZoomEnabled = false
self.mapView.interactionOptions.isRotateEnabled = false
}
}
}
}
}
// MARK: - Actions
@IBAction func generateGeodatabaseAction(_ sender: UIBarButtonItem) {
if sender.title == "Generate Geodatabase" {
// Show the instructions label and update the text.
instructionsLabel.isHidden = false
instructionsLabel.text = "Choose an extent by keeping the desired area within the shown block"
// Show the extent view.
extentView.isHidden = false
// Update to "Done" button.
sender.title = "Done"
} else if sender.title == "Done" {
performSegue(withIdentifier: "FeatureLayersSegue", sender: self)
}
}
private func generateGeodatabase(_ layerIDs: [Int], extent: AGSEnvelope) {
// Create AGSGenerateLayerOption objects with selected layerIds.
var layerOptions = [AGSGenerateLayerOption]()
for layerID in layerIDs {
let layerOption = AGSGenerateLayerOption(layerID: layerID)
layerOptions.append(layerOption)
}
// Set the parameters.
let params = AGSGenerateGeodatabaseParameters()
params.extent = extent
params.layerOptions = layerOptions
params.returnAttachments = true
params.attachmentSyncDirection = .bidirectional
// Name the geodatabase.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let downloadFileURL = documentDirectoryURL
.appendingPathComponent(dateFormatter.string(from: Date()))
.appendingPathExtension("geodatabase")
guard let syncTask = syncTask else {
return
}
// Create a generate job from the sync task.
let generateJob = syncTask.generateJob(with: params, downloadFileURL: downloadFileURL)
self.generateJob = generateJob
// Start the job.
generateJob.start(statusHandler: { (status) in
UIApplication.shared.showProgressHUD(message: status.statusString())
}, completion: { [weak self] (object, error) in
UIApplication.shared.hideProgressHUD()
guard let self = self else {
return
}
if let error = error {
self.presentAlert(error: error)
} else if let geodatabase = object {
// Save a reference to the geodatabase.
self.generatedGeodatabase = geodatabase
// Add the layers from geodatabase.
self.displayLayersFromGeodatabase()
}
})
}
@IBAction func switchToServiceMode(_ sender: AnyObject) {
if generatedGeodatabase?.hasLocalEdits() == true {
let yesAction = UIAlertAction(title: "Yes", style: .default) { [weak self] _ in
self?.syncAction {
self?.switchToServiceMode()
}
}
let noAction = UIAlertAction(title: "No", style: .cancel) { [weak self] _ in
self?.switchToServiceMode()
}
// Ask if changes should be synced before switching to service mode.
let alert = UIAlertController(title: nil, message: "Would you like to sync the changes before switching?", preferredStyle: .alert)
alert.addAction(noAction)
alert.addAction(yesAction)
self.present(alert, animated: true)
} else {
switchToServiceMode()
}
}
@IBAction func syncAction() {
syncAction(nil)
}
private func syncAction(_ completion: (() -> Void)?) {
guard let generatedGeodatabase = generatedGeodatabase,
let syncTask = syncTask else {
return
}
if !generatedGeodatabase.hasLocalEdits() {
print("No local edits. Syncing anyway to fetch the latest remote data.")
}
var syncLayerOptions = [AGSSyncLayerOption]()
for layerInfo in syncTask.featureServiceInfo!.layerInfos {
let layerOption = AGSSyncLayerOption(layerID: layerInfo.id, syncDirection: .bidirectional)
syncLayerOptions.append(layerOption)
}
let params = AGSSyncGeodatabaseParameters()
params.layerOptions = syncLayerOptions
let syncJob = syncTask.syncJob(with: params, geodatabase: generatedGeodatabase)
self.syncJob = syncJob
syncJob.start(statusHandler: { (status) in
UIApplication.shared.showProgressHUD(message: status.statusString())
}, completion: { [weak self] (_, error) in
UIApplication.shared.hideProgressHUD()
if let error = error {
self?.presentAlert(error: error)
} else {
self?.updateUI()
}
// Call completion.
completion?()
})
}
@IBAction func sketchDoneAction() {
navigationItem.hidesBackButton = false
navigationItem.rightBarButtonItem?.isEnabled = true
if let popupsViewController = popupsViewController {
present(popupsViewController, animated: true)
}
NotificationCenter.default.removeObserver(self, name: .AGSSketchEditorGeometryDidChange, object: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let navController = segue.destination as? UINavigationController,
let featureLayerController = navController.viewControllers.first as? FeatureLayersViewController {
featureLayerController.featureLayerInfos = syncTask?.featureServiceInfo?.layerInfos ?? []
featureLayerController.onCompletion = { [weak self] selectedLayerIDs in
if let extent = self?.frameToExtent() {
self?.generateGeodatabase(selectedLayerIDs, extent: extent)
}
}
}
}
}
extension OfflineEditingViewController: AGSGeoViewTouchDelegate {
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
UIApplication.shared.showProgressHUD(message: "Loading")
mapView.identifyLayers(atScreenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false, maximumResultsPerLayer: 10) { [weak self] (results: [AGSIdentifyLayerResult]?, error: Error?) in
UIApplication.shared.hideProgressHUD()
guard let self = self else {
return
}
if let error = error {
self.presentAlert(error: error)
} else if let results = results {
var popups = [AGSPopup]()
for result in results {
for geoElement in result.geoElements {
popups.append(AGSPopup(geoElement: geoElement))
}
}
if !popups.isEmpty {
let popupsViewController = AGSPopupsViewController(popups: popups, containerStyle: .navigationBar)
self.popupsViewController = popupsViewController
popupsViewController.delegate = self
self.present(popupsViewController, animated: true)
} else {
self.presentAlert(message: "No features selected")
}
}
}
}
}
extension OfflineEditingViewController: AGSPopupsViewControllerDelegate {
func popupsViewController(_ popupsViewController: AGSPopupsViewController, sketchEditorFor popup: AGSPopup) -> AGSSketchEditor? {
if let geometry = popup.geoElement.geometry {
// Start sketch editor.
mapView.sketchEditor?.start(with: geometry)
}
return sketchEditor
}
func popupsViewController(_ popupsViewController: AGSPopupsViewController, readyToEditGeometryWith sketchEditor: AGSSketchEditor?, for popup: AGSPopup) {
// Dismiss the popup view controller.
dismiss(animated: true)
// Prepare the current view controller for sketch mode.
mapView.callout.isHidden = true
// Hide the back button.
navigationItem.hidesBackButton = true
// Disable the code button.
navigationItem.rightBarButtonItem?.isEnabled = false
// Unhide the sketch toolbar.
sketchToolbar.isHidden = false
// Disable the "Done" button until any geometry changes.
doneBBI.isEnabled = false
NotificationCenter.default.addObserver(self, selector: #selector(OfflineEditingViewController.sketchChanged(_:)), name: .AGSSketchEditorGeometryDidChange, object: nil)
}
func popupsViewController(_ popupsViewController: AGSPopupsViewController, didFinishEditingFor popup: AGSPopup) {
disableSketchEditor()
let feature = popup.geoElement as! AGSFeature
// Simplify the geometry. This will take care of self intersecting polygons.
feature.geometry = AGSGeometryEngine.simplifyGeometry(feature.geometry!)
// Normalize the geometry. This will take care of geometries that extend beyond the dateline (if wraparound was enabled on the map).
feature.geometry = AGSGeometryEngine.normalizeCentralMeridian(of: feature.geometry!)
// Sync changes if in service mode.
if liveMode {
// Tell the user edits are being saved int the background.
UIApplication.shared.showProgressHUD(message: "Saving feature details...")
(feature.featureTable as! AGSServiceFeatureTable).applyEdits { [weak self] (_, error) in
UIApplication.shared.hideProgressHUD()
if let error = error {
self?.presentAlert(error: error)
} else {
self?.presentAlert(message: "Edits applied successfully")
}
}
} else {
// Update edit count and enable/disable sync button otherwise.
updateUI()
}
}
func popupsViewController(_ popupsViewController: AGSPopupsViewController, didCancelEditingFor popup: AGSPopup) {
disableSketchEditor()
}
func popupsViewControllerDidFinishViewingPopups(_ popupsViewController: AGSPopupsViewController) {
// Dismiss the popups view controller.
dismiss(animated: true)
self.popupsViewController = nil
}
}
|
apache-2.0
|
91c30744cd45c6fa0ff89371dd41ef78
| 39.756863 | 195 | 0.603146 | 5.278314 | false | false | false | false |
chili-ios/CHICore
|
CHICore/Classes/BackgroundService/BackgroundService.swift
|
1
|
1921
|
//
// Created by Igors Nemenonoks on 12/02/16.
// Copyright (c) 2016 Chili. All rights reserved.
//
import Foundation
import UIKit
public protocol PBackgroundService {
var inBackground: Bool { get }
var bgDate: NSDate? { get }
}
public class BackgroundService: PBackgroundService {
private(set) open var inBackground: Bool = false
private(set) open var bgDate: NSDate?
public init() {
registerForEvents()
}
private func registerForEvents() {
NotificationCenter.default.addObserver(self,
selector: #selector(BackgroundService.onAppBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(BackgroundService.onAppDidEnterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
@objc private func onAppBecomeActive(notification: NSNotification) {
if self.inBackground {
let timeInBackground = NSDate.init().timeIntervalSince1970 - self.bgDate!.timeIntervalSince1970
BGApplicationDidBecomeActiveEvent.init(fromBackground: self.inBackground, backgroundTime: timeInBackground).send()
} else {
BGApplicationDidBecomeActiveEvent.init(fromBackground: self.inBackground).send()
}
self.inBackground = false
}
@objc private func onAppDidEnterBackground (notification: NSNotification) {
self.inBackground = true
self.bgDate = NSDate.init()
BGApplicationDidEnterBackgroundEvent.init().send()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
|
mit
|
19ec96bca35fb179c5a302a88fe7ad45
| 34.574074 | 126 | 0.614784 | 5.600583 | false | false | false | false |
valentinknabel/StateMachine
|
Finite.playground/Contents.swift
|
1
|
1937
|
// Playground - noun: a place where people can play
import Finite
enum Test: Int {
case Saving, Fetching, Deleting
case Ready, Fail
}
var machine = StateMachine<Test>(initial: .Ready) { c in
c.allow(from: [.Saving, .Fetching, .Deleting], to: [.Ready, .Fail])
c.allow(from: .Ready, to: [.Saving, .Fetching, .Deleting])
}
machine.onTransitions(from: .Ready) {
print("From Ready: show activity indicator")
}
machine.onTransitions(to: .Ready) {
print("To Ready: hide activity indicator")
}
machine.onTransitions(to: .Saving) {
print("To: save")
}
try machine.transition(to: .Saving) {
print("Triggered: save")
}
machine.state
enum State<T: Hashable>: Hashable {
case Ready
case Error
case Busy(T)
var hashValue: Int {
switch self {
case .Ready:
return 0
case .Error:
return 1
case let .Busy(b):
return 2 + b.hashValue
}
}
var isBusy: Bool {
switch self {
case .Busy(_):
return true
default:
return false
}
}
}
func ==<T>(lhs: State<T>, rhs: State<T>) -> Bool {
switch (lhs, rhs) {
case (.Ready, .Ready):
return true
case (.Error, .Error):
return true
case let (.Busy(lhb), .Busy(rhb)):
return lhb == rhb
default:
return false
}
}
enum Process {
case Saving, Fetching, Deleting
}
var scnd = StateMachine<State<Process>>(initial: .Ready) { flow in
//allow transitions from busy
flow.allow(to: [.Ready, .Error]) { transition in
return transition.from?.isBusy ?? false
}
//allow transitions from ready to busy
flow.allow(from: .Ready) { t in
return t.to?.isBusy ?? false
}
flow.allow(transition: Transition(from: nil, to: .Busy(.Deleting)))
}
do {
try scnd.transition(to: State<Process>.Busy(.Deleting))
} catch {
print(error)
}
|
mit
|
02e84e4e3b357f56999a276b3954c19c
| 20.764045 | 71 | 0.586474 | 3.627341 | false | false | false | false |
filestack/filestack-ios
|
Sources/Filestack/UI/Internal/Controllers/CloudSourceTabBarController.swift
|
1
|
12606
|
//
// CloudSourceTabBarController.swift
// Filestack
//
// Created by Ruben Nine on 11/16/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import FilestackSDK
import UIKit
private struct URLSessionTaskTracker {
private var tasks: [URLSessionTask] = [URLSessionTask]()
private let queue = DispatchQueue(label: "com.filestack.URLSessionTaskTracker")
mutating func add(_ task: URLSessionTask) {
queue.sync { tasks.append(task) }
}
mutating func remove(_ task: URLSessionTask) {
queue.sync { tasks.removeAll { $0 == task } }
}
mutating func cancelPendingAndRemove() {
queue.sync {
for request in tasks {
request.cancel()
}
tasks.removeAll()
}
}
}
class CloudSourceTabBarController: UITabBarController, CloudSourceDataSource {
var client: Client!
var storeOptions: StorageOptions!
var source: CloudSource!
var path: String!
var nextPageToken: String?
var customSourceName: String?
var viewType: CloudSourceViewType!
let thumbnailCache: NSCache<NSURL, UIImage> = {
let cache = NSCache<NSURL, UIImage>()
cache.countLimit = 1000
return cache
}()
private(set) var items: [CloudItem]?
private var requestInProgress: Bool {
return currentRequest != nil
}
private let session = URLSession.filestackDefault
private var toggleViewTypeButton: UIBarButtonItem?
private var currentRequest: Cancellable?
private var thumbnailTasks = URLSessionTaskTracker()
private weak var uploadMonitorViewController: MonitorViewController?
private var uploaderObserver: NSKeyValueObservation?
// MARK: - View Overrides
override func viewDidLoad() {
super.viewDidLoad()
// For all the sources except the custom source, we obtain its name by asking about its description,
// however, for the custom source name we obtain this value separately.
if source == .customSource, customSourceName != nil {
title = customSourceName
} else {
title = source.description
}
// Hide tab bar (we will toggle between views using our custom list/grid toggle button.)
tabBar.isHidden = true
// Replace default back button with one with a custom title
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
// Add logout button (unless we are displaying the custom source)
if source != .customSource {
let logoutImage = UIImage(named: "icon-logout", in: bundle, compatibleWith: nil)
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: logoutImage, style: .plain, target: self, action: #selector(logout)),
]
} else {
navigationItem.rightBarButtonItems = []
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
selectedIndex = (source.provider.viewType ?? viewType).rawValue
if source.provider.viewType == nil {
setupViewTypeButton()
}
guard items == nil else { return }
// Request folder list, and notify the selected view controller when done.
currentRequest = requestFolderList(source: source, path: path) { response in
self.currentRequest = nil
// Got an error, present error and pop to root view controller (i.e., source list selection)
if let error = response.error {
let alert = UIAlertController(title: "Error",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
// Dismiss monitor view controller, and remove strong reference to it
self.navigationController?.popToRootViewController(animated: true)
}))
self.present(alert, animated: true)
return
}
// Ensure we got contents or return early
guard let contents = response.contents else { return }
// Flat map JSON array into CloudItem array.
let items = contents.compactMap { CloudItem(dictionary: $0) }
// Store next page token (or nil, if none)
self.nextPageToken = response.nextToken
// Finally, replace data source items with the latest received items
self.items = items
// Notify any data source consumer childs that the data source (this object) has received initial results.
for child in self.children {
(child as? CloudSourceDataSourceConsumer)?.dataSourceReceivedInitialResults(dataSource: self)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
currentRequest?.cancel()
cancelPendingThumbnailRequests()
super.viewWillDisappear(animated)
}
// MARK: - CloudSourceDataSource Protocol Functions
func store(item: CloudItem) {
guard let picker = navigationController as? PickerNavigationController else { return }
let completionHandler: ((StoreResponse) -> Void) = { response in
self.uploaderObserver = nil
self.uploadMonitorViewController?.dismiss(animated: true) {
self.uploadMonitorViewController = nil
if let error = response.error {
let alert = UIAlertController(title: "Upload Failed",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
picker.pickerDelegate?.pickerStoredFile(picker: picker, response: response)
}))
picker.present(alert, animated: true)
} else {
picker.pickerDelegate?.pickerStoredFile(picker: picker, response: response)
}
}
}
let request = client.store(provider: source.provider,
path: item.path,
storeOptions: storeOptions,
completionHandler: completionHandler)
if uploadMonitorViewController == nil {
let monitorViewController = MonitorViewController(progressable: request)
monitorViewController.modalPresentationStyle = .currentContext
self.uploadMonitorViewController = monitorViewController
picker.present(monitorViewController, animated: true, completion: nil)
}
}
func loadNextPage(completionHandler: @escaping (() -> Void)) {
guard let nextPageToken = nextPageToken, !requestInProgress else { return }
currentRequest = requestFolderList(source: source,
path: path,
pageToken: nextPageToken) { response in
self.currentRequest = nil
guard let contents = response.contents else { return }
let items = contents.compactMap { CloudItem(dictionary: $0) }
self.nextPageToken = response.nextToken
self.items?.append(contentsOf: items)
completionHandler()
}
}
func refresh(completionHandler: @escaping (() -> Void)) {
guard !requestInProgress, items != nil else { return }
cancelPendingThumbnailRequests()
currentRequest = requestFolderList(source: source, path: path) { response in
self.currentRequest = nil
guard let contents = response.contents else { return }
let items = contents.compactMap { CloudItem(dictionary: $0) }
self.nextPageToken = response.nextToken
self.items = items
completionHandler()
}
}
func cacheThumbnail(for item: CloudItem, completionHandler: @escaping ((UIImage) -> Void)) {
let cachePolicy = client.config.cloudThumbnailCachePolicy
let urlRequest = URLRequest(url: item.thumbnailURL, cachePolicy: cachePolicy)
// Request thumbnail
var task: URLSessionDataTask!
task = URLSession.filestackDefault.dataTask(with: urlRequest) { (data, response, error) in
// Remove request from thumbnail requests
self.thumbnailTasks.remove(task)
var image: UIImage!
// Obtain image from data, and square it.
if error == nil, let data = data, let squareImage = UIImage(data: data)?.squared {
image = squareImage
} else {
// Unable to obtain image, use file placeholder.
image = UIImage(named: "file", in: bundle, compatibleWith: nil)
}
// Update thumbnail cache with image.
self.thumbnailCache.setObject(image, forKey: item.thumbnailURL as NSURL)
// Call completion handler
DispatchQueue.main.async { completionHandler(image) }
}
task.resume()
// Add request to thumbnail requests.
thumbnailTasks.add(task)
}
func search(text: String, completionHandler: @escaping (() -> Void)) {
guard let escapedText = text.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return }
path = "/\(escapedText)/"
refresh(completionHandler: completionHandler)
}
func navigate(to item: CloudItem) {
let scene = CloudSourceTabBarScene(client: client,
storeOptions: storeOptions,
source: source,
customSourceName: customSourceName,
path: item.path,
nextPageToken: nil,
viewType: viewType)
if let vc = storyboard?.instantiateViewController(for: scene) {
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - Private Functions
private func alternateIcon() -> UIImage {
let alternateViewtype = viewType.toggle()
return UIImage.fromFilestackBundle(alternateViewtype.iconName)
}
private func setupViewTypeButton() {
if toggleViewTypeButton == nil {
toggleViewTypeButton = UIBarButtonItem(image: alternateIcon(), style: .plain, target: self, action: #selector(toggleViewType))
navigationItem.rightBarButtonItems?.append(toggleViewTypeButton!)
} else {
toggleViewTypeButton?.image = alternateIcon()
}
}
private func requestFolderList(source: CloudSource,
path: String,
pageToken: String? = nil,
completionHandler: @escaping FolderListCompletionHandler) -> Cancellable {
return client.folderList(provider: source.provider,
path: path,
pageToken: pageToken,
queue: .main,
completionHandler: completionHandler)
}
private func cancelPendingThumbnailRequests() {
thumbnailTasks.cancelPendingAndRemove()
}
// MARK: - Actions
@IBAction func toggleViewType(_: Any) {
viewType = viewType.toggle()
selectedIndex = viewType.rawValue
setupViewTypeButton()
// Store view type in user defaults
UserDefaults.standard.set(cloudSourceViewType: viewType)
}
@IBAction func logout(_: Any) {
client.logout(provider: source.provider) { response in
if let error = response.error {
let alert = UIAlertController(title: "Logout Failed",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
} else {
self.navigationController?.popToRootViewController(animated: true)
}
}
}
}
|
mit
|
4f68835d3932967d8042666f06da37fc
| 36.073529 | 138 | 0.591194 | 5.607206 | false | false | false | false |
belatrix/BelatrixEventsIOS
|
Hackatrix/Controller/LocationVC.swift
|
1
|
1481
|
//
// LocationVC.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 19/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LocationVC: UIViewController {
//MARK: - Properties
@IBOutlet weak var tableViewLocation: UITableView!
var cities:[City] = []
var itemSelected:IndexPath!
//MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension LocationVC: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Localización"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.cell.location) as! LocationCell
cell.locationName.text = self.cities[indexPath.row].name
if indexPath.row == 0 {
cell.accessoryType = .checkmark
self.itemSelected = indexPath
}
return cell
}
}
extension LocationVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
apache-2.0
|
9c8d95ec8c1487f5c007206c41dc3386
| 23.65 | 100 | 0.656525 | 4.897351 | false | false | false | false |
plutoless/fgo-pluto
|
FgoPluto/FgoPluto/model/Plan.swift
|
1
|
1599
|
//
// Plan.swift
// FgoPluto
//
// Created by Zhang, Qianze on 12/10/2017.
// Copyright © 2017 Plutoless Studio. All rights reserved.
//
import Foundation
import RealmSwift
class Plan : BaseObject
{
//group id is used to bundle multiple plan items into one
//they will share the same group id
let servants = List<Servant>()
//as realm does not support array of primitive types
//we store the plan numbers as a string like below
//ad_from, ad_to, skill1_from, skill1_to, skill2_from, skill2_to, skill3_from, skill3_to
dynamic var archived_plan:String = "0,0,0,0,0,0"
var plan:[[PlanRange]]?{
var result_plans:[[PlanRange]] = []
let plans:[String] = self.archived_plan.components(separatedBy: ";")
for plan:String in plans{
let plan_values:[String] = plan.components(separatedBy: ",")
if(plan_values.count != 6){
return nil
}
var result_plan:[PlanRange] = []
var plan_int_vals:[Int] = []
for i in 0..<plan_values.count{
let val_str:String = plan_values[i]
guard let val:Int = Int(val_str) else {return nil}
plan_int_vals.append(val)
if(i % 2 == 1){
result_plan.append((plan_int_vals[i - 1], plan_int_vals[i]))
}
}
result_plans.append(result_plan)
}
return result_plans
}
override static func ignoredProperties() -> [String] {
return ["plan"]
}
}
|
apache-2.0
|
b70233a640542ec2e385a2349d995f46
| 30.96 | 92 | 0.551314 | 3.878641 | false | false | false | false |
xusader/firefox-ios
|
Utils/Extensions/UIImage+Extensions.swift
|
3
|
2127
|
/* 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
extension UIImage {
class func createWithColor(size: CGSize, color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
let context = UIGraphicsGetCurrentContext();
let rect = CGRect(origin: CGPointZero, size: size)
color.setFill()
CGContextFillRect(context, rect)
var image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return image
}
}
private class ThumbnailOperation : NSObject, SDWebImageOperation {
var cacheOperation: NSOperation?
var cancelled: Bool {
if let cacheOperation = cacheOperation {
return cacheOperation.cancelled
}
return false
}
@objc func cancel() {
if let cacheOperation = cacheOperation {
cacheOperation.cancel()
}
}
}
// This is an extension to SDWebImage's api to allow passing in a cache to be used for lookup.
public typealias CompletionBlock = (img: UIImage?, err: NSError, type: SDImageCacheType, key: String) -> Void
extension UIImageView {
public func moz_getImageFromCache(url: String, cache: SDImageCache, completed: CompletionBlock) {
self.sd_cancelCurrentImageLoad()
let operation = ThumbnailOperation()
let key = SDWebThumbnails.getKey(url)
operation.cacheOperation = cache.queryDiskCacheForKey(key, done: { (image, cacheType) -> Void in
let err = NSError()
// If this was cancelled, don't bother notifying the caller
if operation.cancelled {
return
}
if let image = image {
self.image = image
self.setNeedsLayout()
}
completed(img: image, err: err, type: cacheType, key: url)
})
self.sd_setImageLoadOperation(operation, forKey: "UIImageViewImageLoad")
}
}
|
mpl-2.0
|
e7ac590521ec69179794c265ffe3954b
| 33.322581 | 109 | 0.64598 | 4.889655 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/Me/Controller/ChangePassWordViewController.swift
|
1
|
4097
|
//
// ChangePassWordViewController.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/13.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class ChangePassWordViewController: UITableViewController {
private let LanCPVCPlaceholder = ["请输入旧密码","请输入8-16位由数字和字母组成的新密码","请再次输入密码"]
private let picArr = ["m_oldPassWord","m_newPassWord","m_resetNewPassWord"]
override func viewDidLoad() {
super.viewDidLoad()
title = "修改密码"
tableView.separatorStyle = .none
tableView.tableFooterView = footerView
footerView.addSubview(confirmBtn)
confirmBtn.snp.makeConstraints { (make) in
make.right.equalTo(self.footerView).offset(-40)
make.left.equalTo(self.footerView).offset(40)
make.top.equalTo(self.footerView).offset(15)
make.height.equalTo(40)
}
}
private lazy var footerView:UIView = {
let footer = UIView()
footer.frame = CGRect(x: 0,y: 0,width: kScreenWidth,height: 70)
return footer
}()
private lazy var confirmBtn:UIButton = {
let btn = UIButton("确定", titleColor: UIColor.white, target: self, action: #selector(ChangePassWordViewController.clickConfirm),needLayer:true)
btn.backgroundColor = kAppearanceColor
return btn
}()
@objc func clickConfirm(){
var passWord = ""
var reSetPassWord = ""
var param = [String:AnyObject]()
for indexNum in 0..<LanCPVCPlaceholder.count{
let cell = tableView.cellForRow(at: IndexPath(row: indexNum, section: 0)) as! PicAndTFTableViewCell
if cell.textTF.text?.count == 0{
SVProgressHUD.showError(LanCPVCPlaceholder[indexNum])
return
}
if indexNum == 0{
param["oldPassword"] = cell.textTF.text as AnyObject?
}else if indexNum == 1{
param["newPassword"] = cell.textTF.text as AnyObject?
passWord = cell.textTF.text!
}else if indexNum == 2{
reSetPassWord = cell.textTF.text!
}
}
if passWord != reSetPassWord{
SVProgressHUD.showError("两次密码不一致")
return
}
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: param,api:"oms-api-v3/user/modifyPassword")) { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if data["msg"] as! String == "OK"{
SVProgressHUD.showSuccess("密码修改成功")
_ = self.navigationController?.popViewController(animated: true)
}else{
SVProgressHUD.showSuccess("密码修改失败")
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = PicAndTFTableViewCell.loadFromNib()
cell.imageName.image = UIImage(named: picArr[indexPath.row])
cell.textTF.placeholder = LanCPVCPlaceholder[indexPath.row]
cell.selectionStyle = .none
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
}
|
mit
|
9d59bb7c14e8b791744fe8d707a28394
| 34.801802 | 150 | 0.559889 | 4.948941 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/Abstract/Game/Abstract/ViewGame.swift
|
1
|
1055
|
import SpriteKit
class ViewGame<T:MGame>:SKView, ViewProtocol
{
weak var layoutLeft:NSLayoutConstraint!
weak var layoutRight:NSLayoutConstraint!
weak var layoutTop:NSLayoutConstraint!
weak var layoutBottom:NSLayoutConstraint!
weak var pushBackground:VPushBackground?
init(controller:ControllerGame<T>)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
showsFPS = false
showsNodeCount = false
ignoresSiblingOrder = true
translatesAutoresizingMaskIntoConstraints = false
showsPhysics = false
guard
let startSceneType:SKScene.Type = controller.model.startSceneType,
let sceneGameType:ViewGameScene<T>.Type = startSceneType as? ViewGameScene<T>.Type
else
{
return
}
let startScene:ViewGameScene = sceneGameType.init(controller:controller)
presentScene(startScene)
}
required init?(coder:NSCoder)
{
return nil
}
}
|
mit
|
4ef3a861832b7b1c689553f6ff92ed28
| 26.051282 | 94 | 0.640758 | 5.275 | false | false | false | false |
10686142/eChance
|
eChance/InternetConnection.swift
|
1
|
1034
|
//
// HomeModel.swift
// Iraffle
//
// Created by Vasco Meerman on 29/06/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import Foundation
import SystemConfiguration
// Source: https://stackoverflow.com/questions/39558868/check-internet-connection-ios-10
func isInternetAvailable() -> Bool
{
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
|
mit
|
c111d75878c678256e1ac6d87d8c882b
| 30.30303 | 88 | 0.718296 | 4.377119 | false | false | false | false |
stephentyrone/swift
|
validation-test/Reflection/reflect_Character.swift
|
3
|
2630
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Character
// RUN: %target-codesign %t/reflect_Character
// RUN: %target-run %target-swift-reflection-test %t/reflect_Character | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
class TestClass {
var t: Character
init(t: Character) {
self.t = t
}
}
var obj = TestClass(t: "A")
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Character.TestClass)
// CHECK-64-LABEL: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=t offset=16
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1
// CHECK-64-NEXT: (field name=_str offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1
// CHECK-64-NEXT: (field name=_guts offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1
// CHECK-64-NEXT: (field name=_object offset=0
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=2147483647 bitwise_takable=1
// CHECK-64-NEXT: (field name=_countAndFlagsBits offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))
// CHECK-64-NEXT: (field name=_object offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647 bitwise_takable=1)))))))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Character.TestClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=t offset=8
// CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32-NEXT: (field name=_str offset=0
// CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=253 bitwise_takable=1
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
|
apache-2.0
|
fd7d21e04a39d13b74d99f746f108937
| 42.833333 | 134 | 0.681369 | 3.371795 | false | true | false | false |
benlangmuir/swift
|
test/Sema/implementation-only-import-inlinable-multifile.swift
|
14
|
4069
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/indirects.swiftmodule %S/Inputs/implementation-only-imports/indirects.swift
// RUN: %target-swift-frontend -emit-module -o %t/directs.swiftmodule -I %t %S/Inputs/implementation-only-imports/directs.swift
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/implementation-only-imports/secondary_file.swift -I %t
@_implementationOnly import directs
// 'indirects' is imported for re-export in a secondary file
// Types
@inlinable
public func testStructFromDirect() {
_ = StructFromDirect() // expected-error {{struct 'StructFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
// expected-error@-1 {{initializer 'init()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testStructFromIndirect() {
_ = StructFromIndirect()
}
@inlinable
public func testAliasFromDirect() {
_ = AliasFromDirect() // expected-error {{type alias 'AliasFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
// expected-error@-1 {{initializer 'init()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testAliasFromIndirect() {
_ = AliasFromIndirect()
}
@inlinable
public func testGenericAliasFromDirect() {
_ = GenericAliasFromDirect<Int>.self // expected-error {{type alias 'GenericAliasFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testGenericAliasFromIndirect() {
let tmp: GenericAliasFromIndirect<Int>?
_ = tmp
}
// Functions
@inlinable
public func testFunctionFromDirect() {
globalFunctionFromDirect() // expected-error {{global function 'globalFunctionFromDirect()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testFunctionFromIndirect() {
globalFunctionFromIndirect()
}
// Variables
@inlinable
public func testVariableFromDirect_get() {
_ = globalVariableFromDirect // expected-error {{var 'globalVariableFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testVariableFromIndirect_get() {
_ = globalVariableFromIndirect
}
@inlinable
public func testVariableFromDirect_set() {
globalVariableFromDirect = 5 // expected-error {{var 'globalVariableFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testVariableFromIndirect_set() {
globalVariableFromIndirect = 5
}
// Extensions
@inlinable
public func testExtensionMethod(s: inout StructFromIndirect) {
s.extensionMethodFromDirect() // expected-error {{instance method 'extensionMethodFromDirect()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testExtensionProperty_get(s: inout StructFromIndirect) {
_ = s.extensionPropertyFromDirect // expected-error {{property 'extensionPropertyFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testExtensionProperty_set(s: inout StructFromIndirect) {
s.extensionPropertyFromDirect = 5 // expected-error {{property 'extensionPropertyFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testExtensionSubscript_get(s: inout StructFromIndirect) {
_ = s[extensionSubscript: 0] // expected-error {{cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
@inlinable
public func testExtensionSubscript_set(s: inout StructFromIndirect) {
s[extensionSubscript: 0] = 5 // expected-error {{cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}}
}
|
apache-2.0
|
4e7155b0c2fcd481bcc45a5727a5b79a
| 38.125 | 193 | 0.773409 | 4.173333 | false | true | false | false |
sameertotey/LimoService
|
LimoService/RequestsTableViewCell.swift
|
1
|
1401
|
//
// RequestsTableViewCell.swift
// LimoService
//
// Created by Sameer Totey on 4/3/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
class RequestsTableViewCell: PFTableViewCell {
@IBOutlet weak var fromTextField: UITextField!
@IBOutlet weak var toTextField: UITextField!
@IBOutlet weak var whenLabel: UILabel!
@IBOutlet weak var statusIndicatorView: StatusIndicatiorView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let fromLabel = UILabel(frame: CGRectZero)
// fromLabel.text = "From: "
// fromLabel.sizeToFit()
let fromImageView = UIImageView(image: UIImage(named: "FromPin"))
// fromImageView.frame = CGRectMake(0, 0, 16, 24)
fromTextField.leftView = fromImageView
fromTextField.leftViewMode = .Always
let toLabel = UILabel(frame: CGRectZero)
// toLabel.text = "To: "
// toLabel.sizeToFit()
let toImageView = UIImageView(image: UIImage(named: "ToPin"))
// toImageView.frame = CGRectMake(0, 0, 14, 20)
toTextField.leftView = toImageView
toTextField.leftViewMode = .Always
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
4a279ef34d906124d67ae2af61bb135d
| 28.1875 | 73 | 0.654532 | 4.490385 | false | false | false | false |
bannzai/xcp
|
xcp/Translator/PBXGroupTranslator.swift
|
1
|
865
|
//
// PBX.GroupTranslator.swift
// xcp
//
// Created by kingkong999yhirose on 2016/12/23.
// Copyright © 2016年 kingkong999yhirose. All rights reserved.
//
import Foundation
public struct PBXGroupTranslator: Translator {
typealias Object = PBX.Group
typealias JsonType = XCProject.JSON
func fromJson(with jsonType: JsonType, allPBX: AllPBX) -> Object {
// TODO:
fatalError("undefined")
}
func toJson(for object: Object) -> JsonType {
var json: XCProject.JSON = [
"isa": object.isa.rawValue,
"children": object.children.map { $0.id },
"sourceTree": object.sourceTree.value
]
if let name = object.name {
json["name"] = name
}
if let path = object.path {
json["path"] = path
}
return json
}
}
|
mit
|
065b398f1833bd88718f060d8a95537a
| 24.352941 | 70 | 0.577726 | 4.144231 | false | false | false | false |
andrebocchini/SwiftChattyOSX
|
SwiftChattyOSX/Search/SearchManager.swift
|
1
|
3125
|
//
// SearchManager.swift
// SwiftChattyOSX
//
// Created by Andre Bocchini on 4/3/16.
// Copyright (c) 2016 Andre Bocchini. All rights reserved.
//
import SwiftChatty
class SearchManager {
private var selectedThreadId = 0
private var selectedPostId = 0
var results = [Thread]()
private var threads = [Thread]() {
didSet {
for (index, var thread) in self.threads.enumerate() {
thread.sort(.ThreadedOldestFirst)
self.threads[index] = thread
}
}
}
var selectedThread: Thread {
for thread in self.threads {
if thread.id == self.selectedThreadId {
return thread
}
}
return Thread()
}
var selectedPost: Post {
for post in self.selectedThread.posts {
if post.id == self.selectedPostId {
return post
}
}
return Post()
}
var firstThread: Thread {
if let thread = self.threads.first {
return thread
}
return Thread()
}
var firstPost: Post {
if let post = self.selectedThread.posts.first {
return post
}
return Post()
}
func selectFirstThread() {
if let firstThread = self.threads.first {
selectThread(firstThread)
}
}
func selectFirstPost() {
selectPost(self.selectedThread.rootPost())
}
func selectThread(thread: Thread) {
self.selectedThreadId = thread.id
selectFirstPost()
}
func selectPost(post: Post) {
self.selectedThreadId = post.threadId
self.selectedPostId = post.id
}
func search(terms: String?, author: String?, parentAuthor: String?, category: ModerationFlag?, limit: Int?, success: () -> Void, failure: (Error) -> Void) {
ChattyService.search(terms, author: author, parentAuthor: parentAuthor, category: category, limit: limit, success: {
(results) in
self.results = self.convertSearchResultsIntoThreads(results)
var resultIds = [Int]()
for result in self.results {
resultIds.append(result.id)
}
ChattyService.getThreads(resultIds, success: {
(threads) in
self.threads = threads
success()
}, failure: {
(error) in
failure(error)
})
}, failure: {
(error) in
failure(error)
})
}
func threadForSearchResult(result: Thread) -> Thread {
for resultThread in self.threads {
if resultThread.id == result.rootPost().threadId {
return resultThread
}
}
return Thread()
}
private func convertSearchResultsIntoThreads(results: [SearchResult]) -> [Thread] {
var threads = [Thread]()
for result in results {
let thread = Thread(searchResult: result)
threads.append(thread)
}
return threads
}
}
|
mit
|
4fe10a89d828bf0823d3b94fe6795740
| 22.503759 | 160 | 0.54368 | 4.685157 | false | false | false | false |
yrchen/edx-app-ios
|
Source/CutomePlayer/OEXVideoPlayerSettings.swift
|
1
|
5067
|
//
// OEXVideoPlayerSettings.swift
// edX
//
// Created by Michael Katz on 9/9/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private let cellId = "CustomCell"
private typealias RowType = (title: String, value: Any)
private struct OEXVideoPlayerSetting {
let title: String
let rows: [RowType]
let isSelected: (row: Int) -> Bool
let callback: (value: Any)->()
}
@objc protocol OEXVideoPlayerSettingsDelegate {
func showSubSettings(chooser: UIAlertController)
func setCaption(language: String)
func setPlaybackSpeed(speed: Float)
func videoInfo() -> OEXVideoSummary
}
private func setupTable(table: UITableView) {
table.layer.cornerRadius = 10
table.layer.shadowColor = UIColor.blackColor().CGColor
table.layer.shadowRadius = 1.0
table.layer.shadowOffset = CGSize(width: 1, height: 1)
table.layer.shadowOpacity = 0.8
table.separatorInset = UIEdgeInsetsZero
table.registerNib(UINib(nibName: "OEXClosedCaptionTableViewCell", bundle: nil), forCellReuseIdentifier: cellId)
}
@objc class OEXVideoPlayerSettings : NSObject {
let optionsTable: UITableView = UITableView(frame: CGRectZero, style: .Plain)
private lazy var settings: [OEXVideoPlayerSetting] = {
self.updateMargins() //needs to be done here because the table loads the data too soon otherwise and it's nil
let speeds = OEXVideoPlayerSetting(title: "Video Speed", rows: [("0.5x", 0.5), ("1.0x", 1.0), ("1.5x", 1.5), ("2.0x", 2.0)], isSelected: { (row) -> Bool in
return false
}) {[weak self] value in
let fltValue = Float(value as! Double)
self?.delegate?.setPlaybackSpeed(fltValue)
}
if let transcripts: [String: String] = self.delegate?.videoInfo().transcripts as? [String: String] {
var rows = [RowType]()
for lang: String in transcripts.keys {
let locale = NSLocale(localeIdentifier: lang)
let displayLang: String = locale.displayNameForKey(NSLocaleLanguageCode, value: lang)!
let item: RowType = (title: displayLang, value: lang)
rows.append(item)
}
let cc = OEXVideoPlayerSetting(title: "Closed Captions", rows: rows, isSelected: { (row) -> Bool in
var selected = false
if let selectedLanguage:String = OEXInterface.getCCSelectedLanguage() {
let lang = rows[row].value as! String
selected = selectedLanguage == lang
}
return selected
}) {[weak self] value in
self?.delegate?.setCaption(value as! String)
}
return [cc, speeds]
} else {
return [speeds]
}
}()
weak var delegate: OEXVideoPlayerSettingsDelegate?
func updateMargins() {
optionsTable.layoutMargins = UIEdgeInsetsZero
}
init(delegate: OEXVideoPlayerSettingsDelegate, videoInfo: OEXVideoSummary) {
self.delegate = delegate
super.init()
optionsTable.dataSource = self
optionsTable.delegate = self
setupTable(optionsTable)
}
}
extension OEXVideoPlayerSettings: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! OEXClosedCaptionTableViewCell
cell.selectionStyle = .None
cell.lbl_Title?.font = UIFont(name: "OpenSans", size: 12)
cell.viewDisable?.backgroundColor = UIColor.whiteColor()
cell.layoutMargins = UIEdgeInsetsZero
cell.backgroundColor = UIColor.whiteColor()
let setting = settings[indexPath.row]
cell.lbl_Title?.text = setting.title
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedSetting = settings[indexPath.row]
let alert = UIAlertController(title: selectedSetting.title, message: nil, preferredStyle: .ActionSheet)
for (i, row) in selectedSetting.rows.enumerate() {
var title = row.title
if selectedSetting.isSelected(row: i) {
//Can't use font awesome here
title = NSString(format: Strings.videoSettingSelected, row.title) as String
}
alert.addAction(UIAlertAction(title: title, style:.Default, handler: { _ in
selectedSetting.callback(value: row.value)
}))
}
alert.addCancelAction()
delegate?.showSubSettings(alert)
}
}
|
apache-2.0
|
1df9d535127de2d5633b7d373c79d43b
| 35.192857 | 164 | 0.63134 | 4.798295 | false | false | false | false |
goRestart/restart-backend-app
|
Sources/FluentStorage/Model/Game/GameAlternativeNameDiskModel.swift
|
1
|
1076
|
import FluentProvider
extension GameAlternativeNameDiskModel {
public static var name: String = "alt_name"
public struct Field {
public static let name = "name"
}
}
public final class GameAlternativeNameDiskModel: Entity {
public let storage = Storage()
public var name: String
public init(name: String) {
self.name = name
}
public init(row: Row) throws {
name = try row.get(Field.name)
id = try row.get(idKey)
}
public func makeRow() throws -> Row {
var row = Row()
try row.set(Field.name, name)
try row.set(idKey, id)
return row
}
}
// MARK: - Preparations
extension GameAlternativeNameDiskModel: Preparation {
public static func prepare(_ database: Fluent.Database) throws {
try database.create(self) { creator in
creator.id()
creator.string(Field.name)
}
}
public static func revert(_ database: Fluent.Database) throws {
try database.delete(self)
}
}
|
gpl-3.0
|
d5c897e66eb84456496dd183c225a45d
| 20.959184 | 68 | 0.596654 | 4.269841 | false | false | false | false |
sjchmiela/call-of-beacons
|
ios/CallOfBeacons/CallOfBeacons/CABasicAnimation+Pulse.swift
|
1
|
740
|
//
// CABasicAnimation+Pulse.swift
// CallOfBeacons
//
// Created by Stanisław Chmiela on 05.06.2016.
// Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved.
//
import Foundation
extension CABasicAnimation {
static func pulseAnimation(duration: NSTimeInterval, fromValue: CGFloat, toValue: CGFloat) -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = duration
animation.fromValue = fromValue
animation.toValue = toValue
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.autoreverses = true
animation.repeatCount = FLT_MAX
return animation
}
}
|
mit
|
b0b26c4e143e60425471084b28bb9deb
| 32.454545 | 116 | 0.722449 | 4.9 | false | false | false | false |
netprotections/atonecon-ios
|
AtoneCon/Sources/Session.swift
|
1
|
1379
|
//
// Session.swift
// AtoneCon
//
// Created by Pham Ngoc Hanh on 7/25/17.
// Copyright © 2017 AsianTech Inc. All rights reserved.
//
import Foundation
import SAMKeychain
internal final class Session {
internal static let shared = Session()
private let service = "AtoneCon"
internal struct Credential {
fileprivate let key = "accessToken"
fileprivate(set) var authToken: String?
internal var isValid: Bool {
guard let authToken = authToken else { return false }
return !authToken.isEmpty
}
}
internal var credential = Credential(authToken: "") {
didSet {
saveCredential()
}
}
private func saveCredential() {
guard credential.isValid else { return }
removeCredential()
let value = credential.authToken ?? ""
SAMKeychain.setPassword(value, forService: service, account: credential.key)
}
internal func loadCredential() {
guard let authToken = SAMKeychain.password(forService: service, account: credential.key) else { return }
credential.authToken = authToken
}
internal func clearCredential() {
credential.authToken = ""
removeCredential()
}
private func removeCredential() {
SAMKeychain.deletePassword(forService: service, account: credential.key)
}
}
|
mit
|
ca65324d9b7c4e214c6c373bbc7dcb26
| 25 | 112 | 0.641509 | 4.801394 | false | false | false | false |
practicalswift/swift
|
stdlib/public/core/StringStorage.swift
|
2
|
24184
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Having @objc stuff in an extension creates an ObjC category, which we don't
// want.
#if _runtime(_ObjC)
internal protocol _AbstractStringStorage : _NSCopying {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
var length: Int { get } // In UTF16 code units.
}
internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */
internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */
@_effects(readonly)
private func _isNSString(_ str:AnyObject) -> UInt8 {
return _swift_stdlib_isNSString(str)
}
#else
internal protocol _AbstractStringStorage {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
}
#endif
extension _AbstractStringStorage {
// ObjC interfaces.
#if _runtime(_ObjC)
@inline(__always)
@_effects(releasenone)
internal func _getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange
) {
_precondition(aRange.location >= 0 && aRange.length >= 0,
"Range out of bounds")
_precondition(aRange.location + aRange.length <= Int(count),
"Range out of bounds")
let range = Range(
uncheckedBounds: (aRange.location, aRange.location+aRange.length))
let str = asString
str._copyUTF16CodeUnits(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count),
range: range)
}
@inline(__always)
@_effects(releasenone)
internal func _getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt
) -> Int8 {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true):
fallthrough
case (_cocoaUTF8Encoding, _):
guard maxLength >= count + 1 else { return 0 }
outputPtr.initialize(from: start, count: count)
outputPtr[count] = 0
return 1
default:
return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding)
}
}
@inline(__always)
@_effects(readonly)
internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true):
fallthrough
case (_cocoaUTF8Encoding, _):
return start
default:
return _cocoaCStringUsingEncodingTrampoline(self, encoding)
}
}
@_effects(readonly)
internal func _nativeIsEqual<T:_AbstractStringStorage>(
_ nativeOther: T
) -> Int8 {
if count != nativeOther.count {
return 0
}
return (start == nativeOther.start ||
(memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0
}
@inline(__always)
@_effects(readonly)
internal func _isEqual(_ other: AnyObject?) -> Int8 {
guard let other = other else {
return 0
}
if self === other {
return 1
}
// Handle the case where both strings were bridged from Swift.
// We can't use String.== because it doesn't match NSString semantics.
let knownOther = _KnownCocoaString(other)
switch knownOther {
case .storage:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: __StringStorage.self))
case .shared:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: __SharedStringStorage.self))
#if !(arch(i386) || arch(arm))
case .tagged:
fallthrough
#endif
case .cocoa:
// We're allowed to crash, but for compatibility reasons NSCFString allows
// non-strings here.
if _isNSString(other) != 1 {
return 0
}
// At this point we've proven that it is an NSString of some sort, but not
// one of ours.
if length != _stdlib_binary_CFStringGetLength(other) {
return 0
}
defer { _fixLifetime(other) }
// CFString will only give us ASCII bytes here, but that's fine.
// We already handled non-ASCII UTF8 strings earlier since they're Swift.
if let otherStart = _cocoaUTF8Pointer(other) {
return (start == otherStart ||
(memcmp(start, otherStart, count) == 0)) ? 1 : 0
}
/*
The abstract implementation of -isEqualToString: falls back to -compare:
immediately, so when we run out of fast options to try, do the same.
We can likely be more clever here if need be
*/
return _cocoaStringCompare(self, other) == 0 ? 1 : 0
}
}
#endif //_runtime(_ObjC)
}
private typealias CountAndFlags = _StringObject.CountAndFlags
//
// TODO(String docs): Documentation about the runtime layout of these instances,
// which is a little complex. The second trailing allocation holds an
// Optional<_StringBreadcrumbs>.
//
// NOTE: older runtimes called this class _StringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __StringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
#if arch(i386) || arch(arm)
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
internal var _realCapacity: Int
internal var _count: Int
internal var _flags: UInt16
internal var _reserved: UInt16
@inline(__always)
internal var count: Int { return _count }
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
// The capacity of our allocation. Note that this includes the nul-terminator,
// which is not available for overriding.
internal var _realCapacityAndFlags: UInt64
internal var _countAndFlags: _StringObject.CountAndFlags
@inline(__always)
internal var count: Int { return _countAndFlags.count }
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
@inline(__always)
internal var _realCapacity: Int {
return Int(truncatingIfNeeded:
_realCapacityAndFlags & CountAndFlags.countMask)
}
#endif
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var length: Int {
@_effects(readonly) @inline(__always) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other: AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While __StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
private init(_doNotCallMe: ()) {
_internalInvariantFailure("Use the create method")
}
deinit {
_breadcrumbsAddress.deinitialize(count: 1)
}
}
// Determine the actual number of code unit capacity to request from malloc. We
// round up the nearest multiple of 8 that isn't a mulitple of 16, to fully
// utilize malloc's small buckets while accounting for the trailing
// _StringBreadCrumbs.
//
// NOTE: We may still under-utilize the spare bytes from the actual allocation
// for Strings ~1KB or larger, though at this point we're well into our growth
// curve.
private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int {
#if arch(i386) || arch(arm)
// FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so
// that the instance size will be a multiple of 4.
let bias = Int(bitPattern: _StringObject.nativeBias)
let minimum = bias + desiredCapacity + 1
let size = (minimum + 3) & ~3
_internalInvariant(size % 4 == 0)
let capacity = size - bias
_internalInvariant(capacity > desiredCapacity)
return capacity
#else
// Bigger than _SmallString, and we need 1 extra for nul-terminator.
let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity)
_internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length")
// Round up to the nearest multiple of 8 that isn't also a multiple of 16.
let capacity = ((minCap + 7) & -16) + 8
_internalInvariant(
capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0)
return capacity
#endif
}
// Creation
extension __StringStorage {
@_effects(releasenone)
private static func create(
realCodeUnitCapacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
let storage = Builtin.allocWithTailElems_2(
__StringStorage.self,
realCodeUnitCapacity._builtinWordValue, UInt8.self,
1._builtinWordValue, Optional<_StringBreadcrumbs>.self)
#if arch(i386) || arch(arm)
storage._realCapacity = realCodeUnitCapacity
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._realCapacityAndFlags =
UInt64(truncatingIfNeeded: realCodeUnitCapacity)
storage._countAndFlags = countAndFlags
#endif
storage._breadcrumbsAddress.initialize(to: nil)
storage.terminator.pointee = 0 // nul-terminated
// NOTE: We can't _invariantCheck() now, because code units have not been
// initialized. But, _StringGuts's initializer will.
return storage
}
@_effects(releasenone)
private static func create(
capacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
_internalInvariant(capacity >= countAndFlags.count)
let realCapacity = determineCodeUnitCapacity(capacity)
_internalInvariant(realCapacity > capacity)
return __StringStorage.create(
realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags)
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>,
capacity: Int,
isASCII: Bool
) -> __StringStorage {
let countAndFlags = CountAndFlags(
mortalCount: bufPtr.count, isASCII: isASCII)
_internalInvariant(capacity >= bufPtr.count)
let storage = __StringStorage.create(
capacity: capacity, countAndFlags: countAndFlags)
let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
storage.mutableStart.initialize(from: addr, count: bufPtr.count)
storage._invariantCheck()
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool
) -> __StringStorage {
return __StringStorage.create(
initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII)
}
}
// Usage
extension __StringStorage {
@inline(__always)
private var mutableStart: UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self))
}
private var mutableEnd: UnsafeMutablePointer<UInt8> {
@inline(__always) get { return mutableStart + count }
}
@inline(__always)
internal var start: UnsafePointer<UInt8> {
return UnsafePointer(mutableStart)
}
private final var end: UnsafePointer<UInt8> {
@inline(__always) get { return UnsafePointer(mutableEnd) }
}
// Point to the nul-terminator.
private final var terminator: UnsafeMutablePointer<UInt8> {
@inline(__always) get { return mutableEnd }
}
private var codeUnits: UnsafeBufferPointer<UInt8> {
@inline(__always) get {
return UnsafeBufferPointer(start: start, count: count)
}
}
// @opaque
internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> {
let raw = Builtin.getTailAddr_Word(
start._rawValue,
_realCapacity._builtinWordValue,
UInt8.self,
Optional<_StringBreadcrumbs>.self)
return UnsafeMutablePointer(raw)
}
// The total capacity available for code units. Note that this excludes the
// required nul-terminator.
internal var capacity: Int {
return _realCapacity &- 1
}
// The unused capacity available for appending. Note that this excludes the
// required nul-terminator.
//
// NOTE: Callers who wish to mutate this storage should enfore nul-termination
private var unusedStorage: UnsafeMutableBufferPointer<UInt8> {
@inline(__always) get {
return UnsafeMutableBufferPointer(
start: mutableEnd, count: unusedCapacity)
}
}
// The capacity available for appending. Note that this excludes the required
// nul-terminator.
internal var unusedCapacity: Int {
get { return _realCapacity &- count &- 1 }
}
#if !INTERNAL_CHECKS_ENABLED
@inline(__always) internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self))
let rawStart = UnsafeRawPointer(start)
_internalInvariant(unusedCapacity >= 0)
_internalInvariant(count <= capacity)
_internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart)
_internalInvariant(self._realCapacity > self.count, "no room for nul-terminator")
_internalInvariant(self.terminator.pointee == 0, "not nul terminated")
_countAndFlags._invariantCheck()
if isASCII {
_internalInvariant(_allASCII(self.codeUnits))
}
if let crumbs = _breadcrumbsAddress.pointee {
crumbs._invariantCheck(for: self.asString)
}
_internalInvariant(_countAndFlags.isNativelyStored)
_internalInvariant(_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
// Appending
extension __StringStorage {
// Perform common post-RRC adjustments and invariant enforcement.
@_effects(releasenone)
private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) {
let countAndFlags = CountAndFlags(
mortalCount: newCount, isASCII: newIsASCII)
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
self.terminator.pointee = 0
// TODO(String performance): Consider updating breadcrumbs when feasible.
self._breadcrumbsAddress.pointee = nil
_invariantCheck()
}
// Perform common post-append adjustments and invariant enforcement.
@_effects(releasenone)
private func _postAppendAdjust(
appendedCount: Int, appendedIsASCII isASCII: Bool
) {
let oldTerminator = self.terminator
_postRRCAdjust(
newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII)
_internalInvariant(oldTerminator + appendedCount == self.terminator)
}
@_effects(releasenone)
internal func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
_internalInvariant(self.capacity >= other.count)
let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked
let srcCount = other.count
self.mutableEnd.initialize(from: srcAddr, count: srcCount)
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
@_effects(releasenone)
internal func appendInPlace<Iter: IteratorProtocol>(
_ other: inout Iter, isASCII: Bool
) where Iter.Element == UInt8 {
var srcCount = 0
while let cu = other.next() {
_internalInvariant(self.unusedCapacity >= 1)
unusedStorage[srcCount] = cu
srcCount += 1
}
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
internal func clear() {
_postRRCAdjust(newCount: 0, newIsASCII: true)
}
}
// Removing
extension __StringStorage {
@_effects(releasenone)
internal func remove(from lower: Int, to upper: Int) {
_internalInvariant(lower <= upper)
let lowerPtr = mutableStart + lower
let upperPtr = mutableStart + upper
let tailCount = mutableEnd - upperPtr
lowerPtr.moveInitialize(from: upperPtr, count: tailCount)
_postRRCAdjust(
newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII)
}
// Reposition a tail of this storage from src to dst. Returns the length of
// the tail.
@_effects(releasenone)
internal func _slideTail(
src: UnsafeMutablePointer<UInt8>,
dst: UnsafeMutablePointer<UInt8>
) -> Int {
_internalInvariant(dst >= mutableStart && src <= mutableEnd)
let tailCount = mutableEnd - src
dst.moveInitialize(from: src, count: tailCount)
return tailCount
}
@_effects(releasenone)
internal func replace(
from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8>
) {
_internalInvariant(lower <= upper)
let replCount = replacement.count
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
lowerPtr.moveInitialize(
from: UnsafeMutablePointer(
mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked),
count: replCount)
let isASCII = self.isASCII && _allASCII(replacement)
_postRRCAdjust(newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
@_effects(releasenone)
internal func replace<C: Collection>(
from lower: Int,
to upper: Int,
with replacement: C,
replacementCount replCount: Int
) where C.Element == UInt8 {
_internalInvariant(lower <= upper)
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
var isASCII = self.isASCII
var srcCount = 0
for cu in replacement {
if cu >= 0x80 { isASCII = false }
lowerPtr[srcCount] = cu
srcCount += 1
}
_internalInvariant(srcCount == replCount)
_postRRCAdjust(
newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
}
// For shared storage and bridging literals
// NOTE: older runtimes called this class _SharedStringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __SharedStringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
internal var _owner: AnyObject?
internal var start: UnsafePointer<UInt8>
#if arch(i386) || arch(arm)
internal var _count: Int
internal var _flags: UInt16
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
internal var _countAndFlags: _StringObject.CountAndFlags
#endif
internal var _breadcrumbs: _StringBreadcrumbs? = nil
internal var count: Int { return _countAndFlags.count }
internal init(
immortal ptr: UnsafePointer<UInt8>,
countAndFlags: _StringObject.CountAndFlags
) {
self._owner = nil
self.start = ptr
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
super.init()
self._invariantCheck()
}
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var length: Int {
@_effects(readonly) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other:AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While __StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
}
extension __SharedStringStorage {
#if !INTERNAL_CHECKS_ENABLED
@inline(__always)
internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
if let crumbs = _breadcrumbs {
crumbs._invariantCheck(for: self.asString)
}
_countAndFlags._invariantCheck()
_internalInvariant(!_countAndFlags.isNativelyStored)
_internalInvariant(!_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
|
apache-2.0
|
36d15e35c00d6b82839b58e26442c4a8
| 28.930693 | 85 | 0.689423 | 4.256997 | false | false | false | false |
lfaoro/Cast
|
Cast/MenuSendersAction.swift
|
1
|
4224
|
//
// Created by Leonardo on 18/07/2015.
// Copyright © 2015 Leonardo Faoro. All rights reserved.
//
import Cocoa
import RxSwift
final class MenuSendersAction: NSObject {
let shortenClient = ShortenClient()
func shareClipboardContentsAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item, isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func updateGistAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item,
updateGist: true,
isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func shortenURLAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
guard let url = NSURL(string: item) else { fallthrough }
self.shortenClient.shorten(URL: url)
.subscribe { event in
switch event {
case .Next(let shortenedURL):
guard let URL = shortenedURL else { fallthrough }
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL,
title: "Shortened with \(app.prefs.shortenService!)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
default:
app.userNotification.pushNotification(error: "Not a valid URL")
}
})
}
func loginToGithub(sender: NSMenuItem) {
app.oauth.authorize()
}
func logoutFromGithub(sender: NSMenuItem) {
if let error = OAuthClient.revoke() {
app.userNotification.pushNotification(error: error.localizedDescription)
} else {
app.statusBarItem.menu = createMenu(app.menuSendersAction)
app.userNotification.pushNotification(error: "GitHub Authentication",
description: "API key revoked internally")
}
}
func recentUploadsAction(sender: NSMenuItem) {
if let url = sender.representedObject as? NSURL {
NSWorkspace.sharedWorkspace().openURL(url)
} else {
fatalError("No link in recent uploads")
}
}
func clearItemsAction(sender: NSMenuItem) {
if app.prefs.recentActions!.count > 0 {
app.prefs.recentActions!.removeAll()
Swift.print(app.prefs.recentActions!)
app.statusBarItem.menu = createMenu(app.menuSendersAction)
}
}
func startAtLoginAction(sender: NSMenuItem) {
if sender.state == 0 {
sender.state = 1
} else {
sender.state = 0
}
}
func optionsAction(sender: NSMenuItem) {
NSApp.activateIgnoringOtherApps(true)
app.optionsWindowController.showWindow(nil)
}
}
|
mit
|
94f6f96b8325131a14d44ced949d8dbe
| 23.410405 | 78 | 0.656405 | 3.603242 | false | false | false | false |
KingMarney/SwiftTasksNotePad
|
TaskNotePad/AppDelegate.swift
|
1
|
7172
|
//
// AppDelegate.swift
// TaskNotePad
//
// Created by Paul Marney on 8/14/14.
// Copyright (c) 2014 Exmaples. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
//AIzaSyAnRQLf7EiCP_Cehy2zF75F0nZWSon60JA
GMSServices.provideAPIKey("AIzaSyAnRQLf7EiCP_Cehy2zF75F0nZWSon60JA");
// 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.
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("TaskNotePad", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TaskNotePad.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
|
mit
|
a023d7fb10cdc559aaea9b28580dba09
| 51.735294 | 285 | 0.703151 | 5.97169 | false | false | false | false |
mercadopago/sdk-ios
|
MercadoPagoSDK/MercadoPagoSDK/IdentificationService.swift
|
3
|
940
|
//
// IdentificationService.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 5/2/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
public class IdentificationService : MercadoPagoService {
public func getIdentificationTypes(method: String = "GET", uri : String = "/identification_types", public_key : String?, privateKey: String?, success: (jsonResult: AnyObject?) -> Void, failure: ((error: NSError) -> Void)?) {
var params : String? = nil
if public_key != nil {
params = "public_key=" + public_key!
}
if privateKey != nil {
if params != nil {
params = params! + "&"
} else {
params = ""
}
params = params! + "access_token=" + privateKey!
}
self.request(uri, params: params, body: nil, method: method, success: success, failure: failure)
}
}
|
mit
|
a11788190d8d702d1de80d1f92eedbf2
| 35.192308 | 228 | 0.582979 | 4.234234 | false | false | false | false |
austinzheng/swift
|
test/Profiler/instrprof_operators.swift
|
4
|
2103
|
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership -profile-generate %s | %FileCheck %s
// CHECK: sil hidden [ossa] @[[F_OPERATORS:.*operators.*]] :
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 2
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
func operators(a : Bool, b : Bool) {
let c = a && b
let d = a || b
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 2
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 1
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
let e = c ? a : b
// CHECK-NOT: builtin "int_instrprof_increment"
}
// CHECK: implicit closure
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}:$s19instrprof_operators0B01a1bySb_SbtFSbyKXEfu_"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 1
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
// CHECK-NOT: builtin "int_instrprof_increment"
// CHECK: implicit closure
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}:$s19instrprof_operators0B01a1bySb_SbtFSbyKXEfu0_"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 1
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
// CHECK-NOT: builtin "int_instrprof_increment"
|
apache-2.0
|
e33e0977ccac1631515e2b6c85d5898b
| 55.837838 | 127 | 0.584879 | 3.24037 | false | false | false | false |
avito-tech/Marshroute
|
Example/NavigationDemo/VIPER/Advertisement/View/AdvertisementView.swift
|
1
|
6881
|
import UIKit
private let ReuseId = "AdvertisementViewCell"
private let tableHeaderHeight: CGFloat = 44
final class AdvertisementView: UIView, UITableViewDelegate, UITableViewDataSource {
private let gradientView = GradientView()
private let patternView = UIView()
private let tableView = UITableView()
private var recommendedSearchResults = [SearchResultsViewData]()
private let placeholderImageView = UIImageView()
// MARK: - Internal
var defaultContentInsets: UIEdgeInsets = .zero {
didSet {
if ProcessInfo().operatingSystemVersion.majorVersion < 13 {
tableView.contentInset.bottom = defaultContentInsets.bottom
tableView.scrollIndicatorInsets.bottom = defaultContentInsets.bottom
}
}
}
// MARK: - Init
init() {
super.init(frame: .zero)
backgroundColor = .white
addSubview(gradientView)
addSubview(patternView)
patternView.isHidden = true
addSubview(placeholderImageView)
placeholderImageView.contentMode = .scaleAspectFill
placeholderImageView.layer.masksToBounds = true
addSubview(tableView)
tableView.rowHeight = 44
tableView.delegate = self
tableView.dataSource = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Internal
func setPatternAssetName(_ assetName: String?) {
if let assetName = assetName, let patternImage = UIImage(named: assetName) {
patternView.backgroundColor = UIColor(patternImage: patternImage)
patternView.isHidden = false
} else {
patternView.isHidden = true
}
}
func setPlaceholderAssetName(_ assetName: String?) {
if let assetName = assetName, let placeholderImage = UIImage(named: assetName) {
placeholderImageView.image = placeholderImage
setNeedsLayout()
}
}
func setBackgroundRGB(_ rgb: (red: Double, green: Double, blue: Double)?) {
guard let color = colorFromRGB(rgb)
else { return }
gradientView.bottomColor = color
}
func setSimilarSearchResults(_ searchResults: [SearchResultsViewData]) {
recommendedSearchResults = searchResults
tableView.reloadData()
setNeedsLayout()
}
func setSimilarSearchResultsHidden(_ hidden: Bool) {
tableView.isHidden = hidden
setNeedsLayout()
}
var peekSourceViews: [UIView] {
return [tableView]
}
func peekDataAt(
location: CGPoint,
sourceView: UIView)
-> RecommendedSearchResultsPeekData?
{
guard let indexPath = tableView.indexPathForRow(at: location)
else { return nil }
guard let cell = tableView.cellForRow(at: indexPath)
else { return nil }
guard indexPath.row < recommendedSearchResults.count
else { return nil }
let recommendedSearchResult = recommendedSearchResults[indexPath.row]
let cellFrameInSourceView = cell.convert(cell.bounds, to: sourceView)
return RecommendedSearchResultsPeekData(
viewData: recommendedSearchResult,
sourceRect: cellFrameInSourceView
)
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
gradientView.frame = bounds
patternView.frame = bounds
if tableView.isHidden {
placeholderImageView.frame = bounds
} else {
let tableHeight =
CGFloat(recommendedSearchResults.count) * tableView.rowHeight
+ CGFloat(tableView.numberOfSections) * tableHeaderHeight
let tableTop = bounds.height - tableHeight
let tableFrame = CGRect(x: 0, y: tableTop, width: bounds.width, height: tableHeight)
tableView.frame = tableFrame
placeholderImageView.frame = CGRect(x: 0, y: defaultContentInsets.top, width: bounds.width, height: tableTop)
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recommendedSearchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: ReuseId)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseId)
cell?.textLabel?.highlightedTextColor = .white
}
let searchResult = recommendedSearchResults[(indexPath as NSIndexPath).row]
let color = colorFromRGB(searchResult.rgb)
cell?.textLabel?.text = searchResult.title
cell?.contentView.backgroundColor = color
return cell!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Рекомендуемые объявления"
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
recommendedSearchResults[(indexPath as NSIndexPath).row].onTap()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableHeaderHeight
}
// MARK: - Private
private func colorFromRGB(_ rgb: (red: Double, green: Double, blue: Double)?) -> UIColor? {
guard let rgb = rgb
else { return nil }
let color = UIColor(
red: CGFloat(rgb.red),
green: CGFloat(rgb.green),
blue: CGFloat(rgb.blue),
alpha: 0.3
)
return color
}
}
private class GradientView: UIView {
var bottomColor: UIColor = .white {
didSet {
if let gradientLayer = layer as? CAGradientLayer {
gradientLayer.colors = [
UIColor.white.cgColor,
bottomColor.withAlphaComponent(0.8).cgColor,
]
gradientLayer.locations = [0, 1]
}
}
}
// MARK: - Layer
override static var layerClass: AnyClass {
return CAGradientLayer.self
}
}
struct RecommendedSearchResultsPeekData {
let viewData: SearchResultsViewData
let sourceRect: CGRect
}
|
mit
|
d6747ebdf9f4d4914afdae155d9c02e9
| 31.046729 | 133 | 0.608924 | 5.57561 | false | false | false | false |
domenicosolazzo/practice-swift
|
HealthKit/Observing changes in HealthKit/Observing changes in HealthKit/ViewController.swift
|
1
|
5694
|
//
// ViewController.swift
// Observing changes in HealthKit
//
// Created by Domenico Solazzo on 08/05/15.
// License MIT
//
import UIKit
import HealthKit
class ViewController: UIViewController {
// Body mass
let weightQuantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
lazy var types: Set<NSObject> = {
return Set<NSObject>(arrayLiteral: self.weightQuantityType!!)
}()
// Health store
lazy var healthStore = HKHealthStore()
// Predicate
lazy var predicate: NSPredicate = {
let now = Date()
let yesterday = (Calendar.current as NSCalendar).date(
byAdding: NSCalendar.Unit.NSDayCalendarUnit,
value: -1,
to: now,
options: NSCalendar.Options.wrapComponents)
return HKQuery.predicateForSamples(
withStart: yesterday,
end: now,
options: HKQueryOptions.strictEndDate)
}()
// Observer Query
lazy var query: HKObserverQuery = {[weak self] in
let strongSelf = self!
return HKObserverQuery(sampleType: strongSelf.weightQuantityType!!,
predicate: strongSelf.predicate,
updateHandler: strongSelf.weightChangedHandler
)
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(nil, readTypes: types, completion: {[weak self]
(succeeded:Bool, error:NSError!) -> Void in
let strongSelf = self!
if succeeded && error != nil{
dispatch_async(dispatch_get_main_queue(),
strongSelf.startObservingWeightChanges)
}else{
if let theError = error{
print("Error \(theError)")
}
}
})
}else{
print("Health data is not available")
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopObservingWeightChanges()
}
func startObservingWeightChanges(){
healthStore.execute(query)
healthStore.enableBackgroundDeliveryForType(weightQuantityType!!,
frequency: HKUpdateFrequency.Immediate) { (succeeded:Bool, error:NSError?) -> Void in
if succeeded{
print("Enabled background delivery of weight changes")
}else{
if let theError = error{
print("Failed to enabled background changes", terminator: "")
print("Error \(theError)")
}
}
} as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void
}
func stopObservingWeightChanges(){
healthStore.stop(query)
healthStore.disableAllBackgroundDeliveryWithCompletion{
(succeeded: Bool, error: NSError!) in
if succeeded{
print("Disabled background delivery of weight changes")
} else {
if let theError = error{
print("Failed to disable background delivery of weight changes. ", terminator: "")
print("Error = \(theError)")
}
}
} as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void as! (Bool, Error?) -> Void
}
// Fetching the changes
func fetchRecordedWeightsInLastDay(){
// Sorting
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)
// Query
let query = HKSampleQuery(sampleType: weightQuantityType!!, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) {[weak self]
(query:HKSampleQuery!, results:[AnyObject]!, error: NSError!) -> Void in
if results.count > 0{
for sample in results as! [HKQuantitySample]{
// Get the weight in kilograms from the quantity
let weightInKilograms = sample.quantity.doubleValueForUnit(
HKUnit.gramUnitWithMetricPrefix(.Kilo)
)
// Get the value of KG, localized for the user
let formatter = NSMassFormatter()
let kilogramSuffix = formatter.unitStringFromValue(weightInKilograms, unit:.Kilogram)
dispatch_async(dispatch_get_main_queue(), {[weak self] in
let strongSelf = self!
print("Weight has been changed to " +
"\(weightInKilograms) \(kilogramSuffix)")
print("Change date = \(sample.startDate)")
})
}
}else{
print("Could not read the user's weight ", terminator: "")
print("or no weight data was available")
}
}
healthStore.executeQuery(query)
}
func weightChangedHandler(_ query: HKObserverQuery!,
completionHandler: HKObserverQueryCompletionHandler!,
error: NSError!){
}
}
|
mit
|
6a5c6e7fdc4adbc0861010e0b11675a5
| 36.708609 | 198 | 0.546365 | 5.544304 | false | false | false | false |
jmgc/swift
|
test/Constraints/diagnostics.swift
|
1
|
63008
|
// RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
// expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}}
// expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}}
// expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}}
// expected-note@-4 {{where 'T' = 'Int'}}
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}}
i) // expected-error{{extra argument in call}}
// Cannot conform to protocols.
f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}}
f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}}
f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}}
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}}
// expected-note@-1 {{required by global function 'f8' where 'T' = 'Tup' (aka '(Int, Double)')}}
f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{type 'Tup' (aka '(Int, Double)') cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x)
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>(
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{unable to infer complex closure return type; add explicit type to disambiguate}} {{21-21=-> <#Result#> }} {{educational-notes=complex-closure-inference}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} expected-note {{did you mean to add a return type?}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{cannot find type 'Nail' in scope}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer type of a closure parameter $0 in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// Diagnose passing an array in lieu of variadic parameters
func variadic(_ x: Int...) {}
func variadicArrays(_ x: [Int]...) {}
func variadicAny(_ x: Any...) {}
struct HasVariadicSubscript {
subscript(_ x: Int...) -> Int {
get { 0 }
}
}
let foo = HasVariadicSubscript()
let array = [1,2,3]
let arrayWithOtherEltType = ["hello", "world"]
variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}}
variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}}
variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
variadic(0, [1,2,3], 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}} {{13-14=}} {{19-20=}}
variadic(0, [1,2,3,], 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}} {{13-14=}} {{19-20=}} {{20-21=}}
variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}}
variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}}
// FIXME: SR-11104
variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}}
// 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}}
variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}}
foo[0, [1,2,3], 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}} {{8-9=}} {{14-15=}}
variadicAny(array)
variadicAny([1,2,3])
variadicArrays(array)
variadicArrays([1,2,3])
variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}}
variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
protocol Proto {}
func f<T: Proto>(x: [T]) {}
func f(x: Int...) {}
f(x: [1,2,3])
// TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads.
// expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-3 {{remove brackets to pass array elements directly}}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}}
// expected-note@-1 {{candidate expects value of type 'Int' for parameter #1}}
static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}}
// expected-note@-1 {{candidate expects value of type 'Int' for parameter #1}}
static func frob(_ a : Int, b : inout Int) -> Color {}
static var svar: Color { return .Red }
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) })
// expected-error@-1 {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}}
// expected-error@-2 {{cannot infer contextual base in reference to member 'Unknown'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function that produces expected type 'Color'; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{no exact matches in call to static method 'overload'}}
let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}}
someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}}
someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
// expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
// TODO(diagnostics): This is a regression from diagnosing missing optional unwrap for `a`, we have to
// re-think the way errors in tuple elements are detected because it's currently impossible to detect
// exactly what went wrong here and aggregate fixes for different elements at the same time.
_ = MyTuple(42, a) // expected-error {{tuple type 'MyTuple' (aka '(Int, String)') is not convertible to tuple type '(Int, String?)'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType)
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
// FIXME(rdar://problem/65688291) - on iOS simulator this diagnostic is flaky,
// either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires`
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{requires that 'AssocTest' conform to 'Equatable'}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}}
a += a +
b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}}
a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}}
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }}
// expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error@+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message) // expected-note {{did you mean to add a return type?}}
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}}
func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{no exact matches in reference to instance method 'value'}}
}
// SR-1255
func foo1255_1() {
return true || false
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 4 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2)
// expected-error@-1 {{generic parameter 'A' could not be inferred}}
// expected-error@-2 {{generic parameter 'B' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<Any, Any>}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}}
let _: Float = lhs * rhs
// expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}}
Int(3) * "0"
struct S {}
// expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 }
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{50-50=Int(}} {{54-54=)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}}
_ = i + 1
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count }
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
// TODO(diagnostics):Figure out what to do when expressions are complex and completely broken
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}}
}
let _ = [i, j, k].reduce(0 as Int?) {
// expected-error@-1{{missing argument label 'into:' in call}}
// expected-error@-2{{cannot convert value of type 'Int?' to expected argument type}}
$0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil))
// expected-error@-1 {{binary operator '+' cannot be applied to two 'Bool' operands}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
// Notes, attached to declarations, explain that there is a difference between Array.init(_:) and
// RangeReplaceableCollection.init(_:) which are both applicable in this case.
let array = [Int](sequence)
// expected-error@-1 {{no exact matches in call to initializer}}
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{'_' can only appear in a pattern or on the left side of an assignment}}
}
do {
struct Array {}
let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}}
// expected-error@-1 {{generic parameter 'Element' could not be inferred}}
struct Error {}
let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
}
// SyntaxSugarTypes with unresolved types
func takesGenericArray<T>(_ x: [T]) {}
takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
func takesNestedGenericArray<T>(_ x: [[T]]) {}
takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}}
func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {}
takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}}
func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {}
takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}}
func takesArrayOfGenericOptionals<T>(_ x: [T?]) {}
takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}}
func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}}
takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-error@-2 {{generic parameter 'U' could not be inferred}}
typealias Z = Int
func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}}
takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}}
takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}}
takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// Void function returns non-void result fix-it
func voidFunc() {
return 1
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}{{16-16= -> <#Return Type#>}}
}
func voidFuncWithArgs(arg1: Int) {
return 1
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}{{33-33= -> <#Return Type#>}}
}
func voidFuncWithCondFlow() {
if Bool.random() {
return 1
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}}
} else {
return 2
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}}
}
}
func voidFuncWithNestedVoidFunc() {
func nestedVoidFunc() {
return 1
// expected-error@-1 {{unexpected non-void return value in void function}}
// expected-note@-2 {{did you mean to add a return type?}}{{24-24= -> <#Return Type#>}}
}
}
// Special cases: These should not offer a note + fix-it
func voidFuncExplicitType() -> Void {
return 1 // expected-error {{unexpected non-void return value in void function}}
}
class ClassWithDeinit {
deinit {
return 0 // expected-error {{unexpected non-void return value in void function}}
}
}
class ClassWithVoidProp {
var propertyWithVoidType: () { return 5 } // expected-error {{unexpected non-void return value in void function}}
}
class ClassWithPropContainingSetter {
var propWithSetter: Int {
get { return 0 }
set { return 1 } // expected-error {{unexpected non-void return value in void function}}
}
}
// https://bugs.swift.org/browse/SR-11964
struct Rect {
let width: Int
let height: Int
}
struct Frame {
func rect(width: Int, height: Int) -> Rect {
Rect(width: width, height: height)
}
let rect: Rect
}
func foo(frame: Frame) {
frame.rect.width + 10.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
}
// Make sure we prefer the conformance failure.
func f11(_ n: Int) {}
func f11<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}}
f11(3, f4) // expected-error {{global function 'f11' requires that 'Int' conform to 'P2'}}
let f12: (Int) -> Void = { _ in } // expected-note {{candidate '(Int) -> Void' requires 1 argument, but 2 were provided}}
func f12<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{candidate requires that 'Int' conform to 'P2' (requirement specified as 'T' == 'P2')}}
f12(3, f4)// expected-error {{no exact matches in call to global function 'f12'}}
// SR-12242
struct SR_12242_R<Value> {}
struct SR_12242_T {}
protocol SR_12242_P {}
func fSR_12242() -> SR_12242_R<[SR_12242_T]> {}
func genericFunc<SR_12242_T: SR_12242_P>(_ completion: @escaping (SR_12242_R<[SR_12242_T]>) -> Void) {
let t = fSR_12242()
completion(t) // expected-error {{cannot convert value of type 'diagnostics.SR_12242_R<[diagnostics.SR_12242_T]>' to expected argument type 'diagnostics.SR_12242_R<[SR_12242_T]>'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('diagnostics.SR_12242_T' and 'SR_12242_T') are expected to be equal}}
}
func assignGenericMismatch() {
var a: [Int]?
var b: [String]
a = b // expected-error {{cannot assign value of type '[String]' to type '[Int]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}}
b = a // expected-error {{cannot assign value of type '[Int]' to type '[String]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
// expected-error@-2 {{value of optional type '[Int]?' must be unwrapped to a value of type '[Int]'}}
// expected-note@-3 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-4 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// [Int] to [String]? argument to param conversion
let value: [Int] = []
func gericArgToParamOptional(_ param: [String]?) {}
gericArgToParamOptional(value) // expected-error {{convert value of type '[Int]' to expected argument type '[String]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
// Inout Expr conversions
func gericArgToParamInout1(_ x: inout [[Int]]) {}
func gericArgToParamInout2(_ x: inout [[String]]) {
gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]' to expected argument type '[[Int]]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}}
}
func gericArgToParamInoutOptional(_ x: inout [[String]]?) {
gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]?' to expected argument type '[[Int]]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}}
// expected-error@-2 {{value of optional type '[[String]]?' must be unwrapped to a value of type '[[String]]'}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
func gericArgToParamInout(_ x: inout [[Int]]) { // expected-note {{change variable type to '[[String]]?' if it doesn't need to be declared as '[[Int]]'}}
gericArgToParamInoutOptional(&x) // expected-error {{cannot convert value of type '[[Int]]' to expected argument type '[[String]]?'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
// expected-error@-2 {{inout argument could be set to a value with a type other than '[[Int]]'; use a value declared as type '[[String]]?' instead}}
}
// SR-12725
struct SR12725<E> {} // expected-note {{arguments to generic parameter 'E' ('Int' and 'Double') are expected to be equal}}
func generic<T>(_ value: inout T, _ closure: (SR12725<T>) -> Void) {}
let arg: Int
generic(&arg) { (g: SR12725<Double>) -> Void in } // expected-error {{cannot convert value of type '(SR12725<Double>) -> Void' to expected argument type '(SR12725<Int>) -> Void'}}
// rdar://problem/62428353 - bad error message for passing `T` where `inout T` was expected
func rdar62428353<T>(_ t: inout T) {
let v = t // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
rdar62428353(v) // expected-error {{cannot pass immutable value as inout argument: 'v' is a 'let' constant}}
}
func rdar62989214() {
struct Flag {
var isTrue: Bool
}
@propertyWrapper @dynamicMemberLookup
struct Wrapper<Value> {
var wrappedValue: Value
subscript<Subject>(
dynamicMember keyPath: WritableKeyPath<Value, Subject>
) -> Wrapper<Subject> {
get { fatalError() }
}
}
func test(arr: Wrapper<[Flag]>, flag: Flag) {
arr[flag].isTrue // expected-error {{cannot convert value of type 'Flag' to expected argument type 'Int'}}
}
}
// SR-5688
func SR5688_1() -> String? { "" }
SR5688_1!.count // expected-error {{function 'SR5688_1' was used as a property; add () to call it}} {{9-9=()}}
func SR5688_2() -> Int? { 0 }
let _: Int = SR5688_2! // expected-error {{function 'SR5688_2' was used as a property; add () to call it}} {{22-22=()}}
|
apache-2.0
|
6c3779d9551cc4a87e019c10508d31eb
| 45.500369 | 228 | 0.671867 | 3.624065 | false | false | false | false |
Ehrippura/firefox-ios
|
Account/FxAClient10.swift
|
2
|
23359
|
/* 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 Alamofire
import Shared
import Foundation
import FxA
import Deferred
import SwiftyJSON
public let FxAClientErrorDomain = "org.mozilla.fxa.error"
public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999,
userInfo: [NSLocalizedDescriptionKey: "Invalid server response"])
let KeyLength: Int = 32
public struct FxALoginResponse {
public let remoteEmail: String
public let uid: String
public let verified: Bool
public let sessionToken: Data
public let keyFetchToken: Data
}
public struct FxAccountRemoteError {
static let AttemptToOperateOnAnUnverifiedAccount: Int32 = 104
static let InvalidAuthenticationToken: Int32 = 110
static let EndpointIsNoLongerSupported: Int32 = 116
static let IncorrectLoginMethodForThisAccount: Int32 = 117
static let IncorrectKeyRetrievalMethodForThisAccount: Int32 = 118
static let IncorrectAPIVersionForThisAccount: Int32 = 119
static let UnknownDevice: Int32 = 123
static let DeviceSessionConflict: Int32 = 124
static let UnknownError: Int32 = 999
}
public struct FxAKeysResponse {
let kA: Data
let wrapkB: Data
}
public struct FxASignResponse {
let certificate: String
}
public struct FxAStatusResponse {
let exists: Bool
}
public struct FxADevicesResponse {
let devices: [FxADevice]
}
public struct FxANotifyResponse {
let success: Bool
}
public struct FxAOAuthResponse {
let accessToken: String
}
public struct FxAProfileResponse {
let email: String
let uid: String
let avatarURL: String?
let displayName: String?
}
public struct FxADeviceDestroyResponse {
let success: Bool
}
// fxa-auth-server produces error details like:
// {
// "code": 400, // matches the HTTP status code
// "errno": 107, // stable application-level error number
// "error": "Bad Request", // string description of the error type
// "message": "the value of salt is not allowed to be undefined",
// "info": "https://docs.dev.lcip.og/errors/1234" // link to more info on the error
// }
public enum FxAClientError {
case remote(RemoteError)
case local(NSError)
}
// Be aware that string interpolation doesn't work: rdar://17318018, much good that it will do.
extension FxAClientError: MaybeErrorType {
public var description: String {
switch self {
case let .remote(error):
let errorString = error.error ?? NSLocalizedString("Missing error", comment: "Error for a missing remote error number")
let messageString = error.message ?? NSLocalizedString("Missing message", comment: "Error for a missing remote error message")
return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>"
case let .local(error):
return "<FxAClientError.Local Error Domain=\(error.domain) Code=\(error.code) \"\(error.localizedDescription)\">"
}
}
}
public struct RemoteError {
let code: Int32
let errno: Int32
let error: String?
let message: String?
let info: String?
var isUpgradeRequired: Bool {
return errno == FxAccountRemoteError.EndpointIsNoLongerSupported
|| errno == FxAccountRemoteError.IncorrectLoginMethodForThisAccount
|| errno == FxAccountRemoteError.IncorrectKeyRetrievalMethodForThisAccount
|| errno == FxAccountRemoteError.IncorrectAPIVersionForThisAccount
}
var isInvalidAuthentication: Bool {
return code == 401
}
var isUnverified: Bool {
return errno == FxAccountRemoteError.AttemptToOperateOnAnUnverifiedAccount
}
}
open class FxAClient10 {
let authURL: URL
let oauthURL: URL
let profileURL: URL
public init(authEndpoint: URL? = nil, oauthEndpoint: URL? = nil, profileEndpoint: URL? = nil) {
self.authURL = authEndpoint ?? ProductionFirefoxAccountConfiguration().authEndpointURL as URL
self.oauthURL = oauthEndpoint ?? ProductionFirefoxAccountConfiguration().oauthEndpointURL as URL
self.profileURL = profileEndpoint ?? ProductionFirefoxAccountConfiguration().profileEndpointURL as URL
}
open class func KW(_ kw: String) -> Data {
return ("identity.mozilla.com/picl/v1/" + kw).utf8EncodedData
}
/**
* The token server accepts an X-Client-State header, which is the
* lowercase-hex-encoded first 16 bytes of the SHA-256 hash of the
* bytes of kB.
*/
open class func computeClientState(_ kB: Data) -> String? {
if kB.count != 32 {
return nil
}
return kB.sha256.subdata(in: 0..<16).hexEncodedString
}
open class func quickStretchPW(_ email: Data, password: Data) -> Data {
var salt = KW("quickStretch")
salt.append(":".utf8EncodedData)
salt.append(email)
return (password as NSData).derivePBKDF2HMACSHA256Key(withSalt: salt as Data!, iterations: 1000, length: 32)
}
open class func computeUnwrapKey(_ stretchedPW: Data) -> Data {
let salt: Data = Data()
let contextInfo: Data = KW("unwrapBkey")
let bytes = (stretchedPW as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(KeyLength))
return bytes!
}
fileprivate class func remoteError(fromJSON json: JSON, statusCode: Int) -> RemoteError? {
if json.error != nil || 200 <= statusCode && statusCode <= 299 {
return nil
}
if let code = json["code"].int32 {
if let errno = json["errno"].int32 {
return RemoteError(code: code, errno: errno,
error: json["error"].string,
message: json["message"].string,
info: json["info"].string)
}
}
return nil
}
fileprivate class func loginResponse(fromJSON json: JSON) -> FxALoginResponse? {
guard json.error == nil,
let uid = json["uid"].string,
let verified = json["verified"].bool,
let sessionToken = json["sessionToken"].string,
let keyFetchToken = json["keyFetchToken"].string else {
return nil
}
return FxALoginResponse(remoteEmail: "", uid: uid, verified: verified,
sessionToken: sessionToken.hexDecodedData, keyFetchToken: keyFetchToken.hexDecodedData)
}
fileprivate class func keysResponse(fromJSON keyRequestKey: Data, json: JSON) -> FxAKeysResponse? {
guard json.error == nil,
let bundle = json["bundle"].string else {
return nil
}
let data = bundle.hexDecodedData
guard data.count == 3 * KeyLength else {
return nil
}
let ciphertext = data.subdata(in: 0..<(2 * KeyLength))
let MAC = data.subdata(in: (2 * KeyLength)..<(3 * KeyLength))
let salt: Data = Data()
let contextInfo: Data = KW("account/keys")
let bytes = (keyRequestKey as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))
let respHMACKey = bytes?.subdata(in: 0..<KeyLength)
let respXORKey = bytes?.subdata(in: KeyLength..<(3 * KeyLength))
guard let hmacKey = respHMACKey,
ciphertext.hmacSha256WithKey(hmacKey) == MAC else {
NSLog("Bad HMAC in /keys response!")
return nil
}
guard let xorKey = respXORKey,
let xoredBytes = ciphertext.xoredWith(xorKey) else {
return nil
}
let kA = xoredBytes.subdata(in: 0..<KeyLength)
let wrapkB = xoredBytes.subdata(in: KeyLength..<(2 * KeyLength))
return FxAKeysResponse(kA: kA, wrapkB: wrapkB)
}
fileprivate class func signResponse(fromJSON json: JSON) -> FxASignResponse? {
guard json.error == nil,
let cert = json["cert"].string else {
return nil
}
return FxASignResponse(certificate: cert)
}
fileprivate class func statusResponse(fromJSON json: JSON) -> FxAStatusResponse? {
guard json.error == nil,
let exists = json["exists"].bool else {
return nil
}
return FxAStatusResponse(exists: exists)
}
fileprivate class func devicesResponse(fromJSON json: JSON) -> FxADevicesResponse? {
guard json.error == nil,
let jsonDevices = json.array else {
return nil
}
let devices = jsonDevices.flatMap { (jsonDevice) -> FxADevice? in
return FxADevice.fromJSON(jsonDevice)
}
return FxADevicesResponse(devices: devices)
}
fileprivate class func notifyResponse(fromJSON json: JSON) -> FxANotifyResponse {
return FxANotifyResponse(success: json.error == nil)
}
fileprivate class func deviceDestroyResponse(fromJSON json: JSON) -> FxADeviceDestroyResponse {
return FxADeviceDestroyResponse(success: json.error == nil)
}
fileprivate class func oauthResponse(fromJSON json: JSON) -> FxAOAuthResponse? {
guard json.error == nil,
let accessToken = json["access_token"].string else {
return nil
}
return FxAOAuthResponse(accessToken: accessToken)
}
fileprivate class func profileResponse(fromJSON json: JSON) -> FxAProfileResponse? {
guard json.error == nil,
let uid = json["uid"].string,
let email = json["email"].string else {
return nil
}
let avatarURL = json["avatar"].string
let displayName = json["displayName"].string
return FxAProfileResponse(email: email, uid: uid, avatarURL: avatarURL, displayName: displayName)
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.fxaUserAgent
let configuration = URLSessionConfiguration.ephemeral
return SessionManager.managerWithUserAgent(ua, configuration: configuration)
}()
open func login(_ emailUTF8: Data, quickStretchedPW: Data, getKeys: Bool) -> Deferred<Maybe<FxALoginResponse>> {
let authPW = (quickStretchedPW as NSData).deriveHKDFSHA256Key(withSalt: Data(), contextInfo: FxAClient10.KW("authPW"), length: 32) as NSData
let parameters = [
"email": NSString(data: emailUTF8, encoding: String.Encoding.utf8.rawValue)!,
"authPW": authPW.base16EncodedString(options: NSDataBase16EncodingOptions.lowerCase) as NSString,
]
var URL: URL = self.authURL.appendingPathComponent("/account/login")
if getKeys {
var components = URLComponents(url: URL, resolvingAgainstBaseURL: false)!
components.query = "keys=true"
URL = components.url!
}
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = JSON(parameters).stringValue()?.utf8EncodedData
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.loginResponse)
}
open func status(forUID uid: String) -> Deferred<Maybe<FxAStatusResponse>> {
let statusURL = self.authURL.appendingPathComponent("/account/status").withQueryParam("uid", value: uid)
var mutableURLRequest = URLRequest(url: statusURL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.statusResponse)
}
open func devices(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevicesResponse>> {
let URL = self.authURL.appendingPathComponent("/account/devices")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.devicesResponse)
}
open func notify(deviceIDs: [GUID], collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let httpBody = JSON([
"to": deviceIDs,
"payload": [
"version": 1,
"command": "sync:collection_changed",
"data": [
"collections": collections,
"reason": reason
]
]
])
return self.notify(httpBody: httpBody, withSessionToken: sessionToken)
}
open func notifyAll(ownDeviceId: GUID, collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let httpBody = JSON([
"to": "all",
"excluded": [ownDeviceId],
"payload": [
"version": 1,
"command": "sync:collection_changed",
"data": [
"collections": collections,
"reason": reason
]
]
])
return self.notify(httpBody: httpBody, withSessionToken: sessionToken)
}
fileprivate func notify(httpBody: JSON, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let URL = self.authURL.appendingPathComponent("/account/devices/notify")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.notifyResponse)
}
open func destroyDevice(ownDeviceId: GUID, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADeviceDestroyResponse>> {
let URL = self.authURL.appendingPathComponent("/account/device/destroy")
var mutableURLRequest = URLRequest(url: URL)
let httpBody: JSON = JSON(["id": ownDeviceId])
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.deviceDestroyResponse)
}
open func registerOrUpdate(device: FxADevice, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevice>> {
let URL = self.authURL.appendingPathComponent("/account/device")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = device.toJSON().stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxADevice.fromJSON)
}
open func oauthAuthorize(withSessionToken sessionToken: NSData, keyPair: RSAKeyPair, certificate: String) -> Deferred<Maybe<FxAOAuthResponse>> {
let audience = self.getAudience(forURL: self.oauthURL)
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience)
let oauthAuthorizationURL = self.oauthURL.appendingPathComponent("/authorization")
var mutableURLRequest = URLRequest(url: oauthAuthorizationURL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = [
"assertion": assertion,
"client_id": AppConstants.FxAiOSClientId,
"response_type": "token",
"scope": "profile",
"ttl": "300"
]
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
guard let httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData else {
return deferMaybe(FxAClientError.local(FxAClientUnknownError))
}
mutableURLRequest.httpBody = httpBody
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.oauthResponse)
}
open func getProfile(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxAProfileResponse>> {
let keyPair = RSAKeyPair.generate(withModulusSize: 1024)!
return self.sign(sessionToken as Data, publicKey: keyPair.publicKey) >>== { signResult in
return self.oauthAuthorize(withSessionToken: sessionToken, keyPair: keyPair, certificate: signResult.certificate) >>== { oauthResult in
let profileURL = self.profileURL.appendingPathComponent("/profile")
var mutableURLRequest = URLRequest(url: profileURL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue("Bearer " + oauthResult.accessToken, forHTTPHeaderField: "Authorization")
return self.makeRequest(mutableURLRequest, responseHandler: FxAClient10.profileResponse)
}
}
}
open func getAudience(forURL URL: URL) -> String {
if let port = URL.port {
return "\(URL.scheme!)://\(URL.host!):\(port)"
} else {
return "\(URL.scheme!)://\(URL.host!)"
}
}
fileprivate func makeRequest<T>(_ request: URLRequest, responseHandler: @escaping (JSON) -> T?) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
alamofire.request(request)
.validate(contentType: ["application/json"])
.responseJSON { response in
withExtendedLifetime(self.alamofire) {
if let error = response.result.error {
deferred.fill(Maybe(failure: FxAClientError.local(error as NSError)))
return
}
if let data = response.result.value {
let json = JSON(data)
if let remoteError = FxAClient10.remoteError(fromJSON: json, statusCode: response.response!.statusCode) {
deferred.fill(Maybe(failure: FxAClientError.remote(remoteError)))
return
}
if let response = responseHandler(json) {
deferred.fill(Maybe(success: response))
return
}
}
deferred.fill(Maybe(failure: FxAClientError.local(FxAClientUnknownError)))
}
}
return deferred
}
}
extension FxAClient10: FxALoginClient {
func keyPair() -> Deferred<Maybe<KeyPair>> {
let result = RSAKeyPair.generate(withModulusSize: 2048)! // TODO: debate key size and extract this constant.
return Deferred(value: Maybe(success: result))
}
open func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> {
let URL = self.authURL.appendingPathComponent("/account/keys")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("keyFetchToken")
let key = (keyFetchToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
let rangeStart = 2 * KeyLength
let keyRequestKey = key.subdata(in: rangeStart..<(rangeStart + KeyLength))
return makeRequest(mutableURLRequest) { FxAClient10.keysResponse(fromJSON: keyRequestKey, json: $0) }
}
open func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> {
let parameters = [
"publicKey": publicKey.jsonRepresentation() as NSDictionary,
"duration": NSNumber(value: OneDayInMilliseconds), // The maximum the server will allow.
]
let url = self.authURL.appendingPathComponent("/certificate/sign")
var mutableURLRequest = URLRequest(url: url)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = (sessionToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.signResponse)
}
}
|
mpl-2.0
|
c8b21d3d60b260df99473cf52be69ce2
| 40.78712 | 179 | 0.645961 | 4.982722 | false | false | false | false |
TheNumberOne/mal
|
swift/env.swift
|
23
|
4412
|
//******************************************************************************
// MAL - env
//******************************************************************************
import Foundation
typealias EnvironmentVars = [MalSymbol: MalVal]
let kSymbolAmpersand = MalSymbol(symbol: "&")
let kNil = MalNil()
let kNilSymbol = MalSymbol(symbol: "")
class Environment {
init(outer: Environment?) {
self.outer = outer
}
func set_bindings(binds: MalSequence, with_exprs exprs: MalSequence) -> MalVal {
for var index = 0; index < binds.count; ++index {
if !is_symbol(binds[index]) { return MalError(message: "an entry in binds was not a symbol: index=\(index), binds[index]=\(binds[index])") }
let sym = binds[index] as! MalSymbol
if sym != kSymbolAmpersand {
if index < exprs.count {
set(sym, exprs[index])
} else {
set(sym, kNil)
}
continue
}
// I keep getting messed up by the following, so here's an
// explanation. We are iterating over two lists, and are at this
// point:
//
// index
// |
// v
// binds: (... & name)
// exprs: (... a b c d e ...)
//
// In the following, we increment index to get to "name", and then
// later decrement it to get to (a b c d e ...)
if ++index >= binds.count { return MalError(message: "found & but no symbol") }
if !is_symbol(binds[index]) { return MalError(message: "& was not followed by a symbol: index=\(index), binds[index]=\(binds[index])") }
let rest_sym = binds[index--] as! MalSymbol
let rest = exprs[index..<exprs.count]
set(rest_sym, MalList(slice: rest))
break
}
return kNil
}
func set(sym: MalSymbol, _ value: MalVal) -> MalVal {
if num_bindings == 0 {
slot_name0 = sym; slot_value0 = value; ++num_bindings
} else if num_bindings == 1 {
if slot_name0 == sym { slot_value0 = value }
else { slot_name1 = sym; slot_value1 = value; ++num_bindings }
} else if num_bindings == 2 {
if slot_name0 == sym { slot_value0 = value }
else if slot_name1 == sym { slot_value1 = value }
else { slot_name2 = sym; slot_value2 = value; ++num_bindings }
} else if num_bindings == 3 {
if slot_name0 == sym { slot_value0 = value }
else if slot_name1 == sym { slot_value1 = value }
else if slot_name2 == sym { slot_value2 = value }
else { slot_name3 = sym; slot_value3 = value; ++num_bindings }
} else if num_bindings == 4 {
if slot_name0 == sym { slot_value0 = value }
else if slot_name1 == sym { slot_value1 = value }
else if slot_name2 == sym { slot_value2 = value }
else if slot_name3 == sym { slot_value3 = value }
else {
data[slot_name0] = slot_value0
data[slot_name1] = slot_value1
data[slot_name2] = slot_value2
data[slot_name3] = slot_value3
data[sym] = value; ++num_bindings
}
} else {
data[sym] = value
}
return value
}
func get(sym: MalSymbol) -> MalVal? {
if num_bindings > 4 { if let val = data[sym] { return val } }
if num_bindings > 3 { if slot_name3 == sym { return slot_value3 } }
if num_bindings > 2 { if slot_name2 == sym { return slot_value2 } }
if num_bindings > 1 { if slot_name1 == sym { return slot_value1 } }
if num_bindings > 0 { if slot_name0 == sym { return slot_value0 } }
return outer?.get(sym)
}
private var outer: Environment?
private var data = EnvironmentVars()
private var num_bindings = 0
private var slot_name0: MalSymbol = kNilSymbol
private var slot_name1: MalSymbol = kNilSymbol
private var slot_name2: MalSymbol = kNilSymbol
private var slot_name3: MalSymbol = kNilSymbol
private var slot_value0: MalVal = kNil
private var slot_value1: MalVal = kNil
private var slot_value2: MalVal = kNil
private var slot_value3: MalVal = kNil
}
|
mpl-2.0
|
00894264c6a38bbdad3e6a77c45b3c59
| 41.019048 | 152 | 0.516092 | 4.070111 | false | false | false | false |
bradleymackey/WWDC-2017
|
EmojiSort.playground/Sources/OptionView.swift
|
1
|
6680
|
import Foundation
import UIKit
/// To be adopted by any reciever that wants to recieve info about when the user selects a new algorithm, trait or speed.
public protocol OptionChangeReactable: class {
func sort(withAlgorithm algorithm:Sorter.Algorithm, trait: Emoji.Trait, speed: AlgorithmSpeed)
func randomisePositions()
/// so the EmojiSortView can update the bar chart
func newTraitTapped(trait:Emoji.Trait)
/// so the emoji teacher can give a bit of explaination before we see it in action
func newAlgorithmTapped(algorithm:Sorter.Algorithm)
}
public final class OptionView: UIView, EmojiSortViewDelegate, TeacherViewDelegate {
// MARK: Delegate
public weak var sortDelegate:OptionChangeReactable?
public weak var teacherDelegate:OptionChangeReactable?
// MARK: Labels
// setup performed once `self` has initalised
private var traitLabel = UILabel(frame: .zero)
private var algorithmLabel = UILabel(frame: .zero)
private var speedLabel = UILabel(frame: .zero)
// MARK: Buttons
// setup performed once `self` has initalised
private var traitButton = UIButton(type: .system)
private var algorithmButton = UIButton(type: .system)
private var speedButton = UIButton(type: .system)
private var sortButton = UIButton(type: .system)
private var randomiseButton = UIButton(type: .system)
private var allButtons:[UIButton] {
return [traitButton,algorithmButton,speedButton,sortButton,randomiseButton]
}
// MARK: State
private var currentAlgorithm:Sorter.Algorithm = .bubbleSort
private var currentTrait:Emoji.Trait = .happiness
private var currentSpeed:AlgorithmSpeed = .medium
// MARK: Blur View
private lazy var effectView: UIVisualEffectView = UIVisualEffectView(frame: self.bounds)
// MARK: Init
public override init(frame:CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor.black.cgColor
setupLabels()
setupButtons()
setupButtonActions()
setupBlur()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Methods
private func setupBlur() {
effectView.effect = UIBlurEffect(style: .light)
self.addSubview(effectView)
}
private func setupLabels() {
var currentOffsetMultiplier = 1
let traitTitles = ["Trait", "Algorithm", "Speed"]
[traitLabel,algorithmLabel,speedLabel].forEach { label in
defer { currentOffsetMultiplier += 1 }
label.text = traitTitles[currentOffsetMultiplier-1]
label.font = UIFont.systemFont(ofSize: 9)
label.textColor = .darkGray
label.textAlignment = .center
label.sizeToFit()
label.center = CGPoint(x: self.frame.width/2, y: (CGFloat(currentOffsetMultiplier)*(self.frame.height/5))-12)
self.addSubview(label)
}
}
private func setupButtons() {
var currentOffsetMultiplier = 1
let states:[CustomStringConvertible] = [currentTrait,currentAlgorithm,currentSpeed]
[traitButton,algorithmButton,speedButton].forEach { button in
defer { currentOffsetMultiplier += 1 }
button.setTitle(states[currentOffsetMultiplier-1].description, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.5
button.sizeToFit()
button.center = CGPoint(x: self.frame.width/2, y: (CGFloat(currentOffsetMultiplier)*(self.frame.height/5)))
self.addSubview(button)
}
currentOffsetMultiplier = 1
let extraButtonTitles = ["Randomise","Sort"]
[randomiseButton,sortButton].forEach { button in
defer { currentOffsetMultiplier += 1 }
button.setTitle(extraButtonTitles[currentOffsetMultiplier-1], for: .normal)
//button.titleLabel?.font = UIFont.systemFontOfSize(16)
button.sizeToFit()
button.center = CGPoint(x: CGFloat(currentOffsetMultiplier)*self.frame.width/3, y: 4*(self.frame.height/5))
self.addSubview(button)
}
}
private func setupButtonActions() {
traitButton.addTarget(self, action: #selector(OptionView.traitButtonPressed), for: .touchUpInside)
algorithmButton.addTarget(self, action: #selector(OptionView.algorithmButtonPressed), for: .touchUpInside)
speedButton.addTarget(self, action: #selector(OptionView.speedButtonPressed), for: .touchUpInside)
randomiseButton.addTarget(self, action: #selector(OptionView.randomiseButtonPressed), for: .touchUpInside)
sortButton.addTarget(self, action: #selector(OptionView.sortButtonPressed), for: .touchUpInside)
}
// MARK: Button Actions
@objc private func traitButtonPressed() {
currentTrait = currentTrait.next()
traitButton.setTitle(currentTrait.description, for: .normal)
let prevCenter = traitButton.center
traitButton.sizeToFit()
traitButton.center = prevCenter
self.sortDelegate?.newTraitTapped(trait: currentTrait)
}
@objc private func algorithmButtonPressed() {
currentAlgorithm = currentAlgorithm.next()
algorithmButton.setTitle(currentAlgorithm.description, for: .normal)
let prevCenter = algorithmButton.center
algorithmButton.sizeToFit()
algorithmButton.center = prevCenter
self.teacherDelegate?.newAlgorithmTapped(algorithm: currentAlgorithm)
}
@objc private func speedButtonPressed() {
currentSpeed = currentSpeed.next()
speedButton.setTitle(currentSpeed.description, for: .normal)
let prevCenter = speedButton.center
speedButton.sizeToFit()
speedButton.center = prevCenter
}
@objc private func randomiseButtonPressed() {
// disable all buttons until sorting completes
allButtons.forEach { $0.isEnabled = false }
self.sortDelegate?.randomisePositions()
self.teacherDelegate?.randomisePositions()
}
@objc private func sortButtonPressed() {
// disable all buttons until sorting completes
allButtons.forEach { $0.isEnabled = false }
self.sortDelegate?.sort(withAlgorithm: currentAlgorithm, trait: currentTrait, speed: currentSpeed)
self.teacherDelegate?.sort(withAlgorithm: currentAlgorithm, trait: currentTrait, speed: currentSpeed)
}
// MARK: EmojiSortViewDelegate
public func sortingComplete() {
allButtons.forEach { $0.isEnabled = true }
}
private var showcasedElement = false
public func showcaseBegan() {
showcasedElement = true
allButtons.forEach { $0.isEnabled = false }
}
public func showcaseEnded() {
showcasedElement = false
allButtons.forEach { $0.isEnabled = true }
}
// MARK: TeacherViewDelegate
public func interactionReady(fadeDuration:TimeInterval) {
UIView.animate(withDuration: fadeDuration, animations: {
self.effectView.effect = nil
}) { (completed) in
self.effectView.removeFromSuperview()
}
}
}
|
mit
|
6fc22043a046d92c5817745fdb7187f3
| 30.809524 | 121 | 0.756287 | 3.908719 | false | false | false | false |
powerytg/Accented
|
Accented/UI/Home/Stream/Layout/PhotoGroupStreamLayout.swift
|
1
|
4468
|
//
// PhotoGroupStreamLayout.swift
// Accented
//
// Generic stream layout in which each collection view section contains a group of photos
// There're no specific headers or footers in this layout
//
// Created by You, Tiangong on 5/26/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class PhotoGroupStreamLayout: StreamLayoutBase {
private let vGap : CGFloat = 20
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepare() {
scrollDirection = .vertical
if collectionView != nil {
fullWidth = collectionView!.bounds.width
}
}
override var collectionViewContentSize : CGSize {
if layoutCache.count == 0 {
return CGSize.zero
}
return CGSize(width: availableWidth, height: contentHeight)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in layoutCache.values {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes.copy() as! UICollectionViewLayoutAttributes)
}
}
return layoutAttributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func generateLayoutAttributesForStreamHeader() {
// Base class has no header
}
override func generateLayoutAttributesForLoadingState() {
if fullWidth == 0 {
fullWidth = UIScreen.main.bounds.width
}
let indexPath = IndexPath(item : 0, section : 0)
let nextY = contentHeight
let loadingCellSize = CGSize(width: availableWidth, height: 150)
let loadingCellAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
loadingCellAttributes.frame = CGRect(x: 0, y: nextY, width: availableWidth, height: loadingCellSize.height)
contentHeight += loadingCellSize.height
layoutCache["loadingCell"] = loadingCellAttributes
}
override func generateLayoutAttributesForTemplates(_ templates : [StreamLayoutTemplate], sectionStartIndex : Int) -> Void {
// Generate header layout attributes if absent
if layoutCache.count == 0 {
generateLayoutAttributesForStreamHeader()
}
// If there's a previous loading indicator, reset its section height to 0
updateCachedLayoutHeight(cacheKey: loadingIndicatorCacheKey, toHeight: 0)
var nextY = contentHeight
var currentSectionIndex = sectionStartIndex
for (templateIndex, template) in templates.enumerated() {
// Cell layout
for (itemIndex, frame) in template.frames.enumerated() {
let indexPath = IndexPath(item: itemIndex, section: currentSectionIndex)
let finalRect = CGRect(x: frame.origin.x + leftMargin, y: frame.origin.y + nextY, width: frame.size.width, height: frame.size.height)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = finalRect
let cellCacheKey = "photo_\(currentSectionIndex)_\(itemIndex)"
layoutCache[cellCacheKey] = attributes
}
nextY += template.height
// Footer layout
let isLastSection = (templateIndex == templates.count - 1)
let footerHeight = isLastSection ? defaultLoadingIndicatorHeight : 0
let footerCacheKey = isLastSection ? loadingIndicatorCacheKey : "section_footer_\(currentSectionIndex)"
let indexPath = IndexPath(item: 0, section: currentSectionIndex)
let footerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: indexPath)
footerAttributes.frame = CGRect(x: 0, y: nextY, width: fullWidth, height: footerHeight)
layoutCache[footerCacheKey] = footerAttributes
nextY += footerHeight + vGap
// Advance to next section
currentSectionIndex += 1
}
// Update content height
contentHeight = nextY
}
}
|
mit
|
f204f31fcc1315ff99dc1329afff5ef1
| 37.179487 | 150 | 0.6454 | 5.597744 | false | false | false | false |
cwwise/CWWeChat
|
CWWeChat/ChatModule/CWChatKit/Message/Layout/CWMessageLayoutSettings.swift
|
2
|
1077
|
//
// CWMessageLayoutSettings.swift
// CWWeChat
//
// Created by chenwei on 2017/7/14.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
/// layout 部分
class CWMessageLayoutSettings {
public static var share = CWMessageLayoutSettings()
var kMessageToLeftPadding: CGFloat
var kMessageToTopPadding: CGFloat
var kMessageToBottomPadding: CGFloat
// 头像
var kAvaterSize: CGSize
// 昵称
var kUsernameSize: CGSize
var kUsernameLeftPadding: CGFloat
var contentTextFont: UIFont
var errorSize: CGSize
private init() {
kAvaterSize = CGSize(width: 40, height: 40)
kMessageToLeftPadding = 10
kMessageToTopPadding = 10
kMessageToBottomPadding = 10
kUsernameSize = CGSize(width: 120, height: 20)
kUsernameLeftPadding = 10
contentTextFont = UIFont.systemFont(ofSize: 16)
errorSize = CGSize(width: 15, height: 15)
}
}
extension CWMessageLayoutSettings {
}
|
mit
|
1b1cff9f8c5c79fa504ca93194617492
| 17.964286 | 55 | 0.632768 | 4.55794 | false | false | false | false |
nameghino/swift-algorithm-club
|
Binary Search/BinarySearch.swift
|
2
|
643
|
/*
Binary Search
Recursively splits the array in half until the value is found.
If there is more than one occurrence of the search key in the array, then
there is no guarantee which one it finds.
Note: The array must be sorted!
*/
func binarySearch<T: Comparable>(a: [T], key: T) -> Int? {
var range = 0..<a.count
while range.startIndex < range.endIndex {
let midIndex = range.startIndex + (range.endIndex - range.startIndex) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
range.startIndex = midIndex + 1
} else {
range.endIndex = midIndex
}
}
return nil
}
|
mit
|
1f39464504502373a2a2236f720eb7c2
| 25.791667 | 77 | 0.654743 | 3.89697 | false | false | false | false |
bigfat/Countdown-Demo
|
Countdown/CountdownTests/MockPresenter.swift
|
1
|
730
|
//
// MockPresenter.swift
// Countdown
//
// Created by Daniele Spagnolo on 04/02/15.
// Copyright (c) 2015 spagosx. All rights reserved.
//
import UIKit
class MockPresenter: Presenter {
var startButtonTapped = false
override func startDidtap() {
startButtonTapped = true
}
var pickedDateCalled = false
override func pickedDate() -> NSDate {
pickedDateCalled = true
return NSDate(timeIntervalSinceNow: 86400)
}
var updateCountdownCalled = false
var countDownArgument: NSTimeInterval = 0
override func updateCountdown(countdown: NSTimeInterval) {
updateCountdownCalled = true
countDownArgument = countdown
}
}
|
mit
|
98c315dea016ca11b34452ed34b0407b
| 20.470588 | 62 | 0.654795 | 4.679487 | false | false | false | false |
Brightify/DataMapper
|
Tests/Core/Transformation/Transformations/Date/ISO8601DateTransformationTest.swift
|
1
|
1593
|
//
// ISO8601DateTransformationTest.swift
// DataMapper
//
// Created by Filip Dolnik on 31.12.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Quick
import Nimble
import DataMapper
class ISO8601DateTransformationTest: QuickSpec {
override func spec() {
describe("ISO8601DateTransformation") {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let transformation = ISO8601DateTransformation()
let value = formatter.date(from: "2016-12-31T11:00:32+01:00")
let type: SupportedType = .string(formatter.string(from: value ?? Date()))
let incorrectType: SupportedType = .double(1)
describe("transform(from)") {
it("transforms correct SupportedType to value") {
expect(transformation.transform(from: type)) == value
}
it("transforms incorrect SupportedType to nil") {
expect(transformation.transform(from: incorrectType)).to(beNil())
}
}
describe("transform(object)") {
it("transforms value to SupportedType") {
expect(transformation.transform(object: value)) == type
}
it("transforms nil to SupportedType.null") {
expect(transformation.transform(object: nil)) == SupportedType.null
}
}
}
}
}
|
mit
|
055367f436292f6ba41d0aa00051498b
| 35.181818 | 87 | 0.567839 | 4.944099 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/AppCoordinator.swift
|
1
|
7300
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import TrustCore
import UIKit
import URLNavigator
class AppCoordinator: NSObject, Coordinator {
let navigationController: NavigationController
lazy var welcomeViewController: WelcomeViewController = {
let controller = WelcomeViewController()
controller.delegate = self
return controller
}()
let pushNotificationRegistrar = PushNotificationsRegistrar()
private let lock = Lock()
private var keystore: Keystore
private var appTracker = AppTracker()
private var navigator: URLNavigatorCoordinator
var inCoordinator: InCoordinator? {
return self.coordinators.compactMap { $0 as? InCoordinator }.first
}
var coordinators: [Coordinator] = []
init(
window: UIWindow,
keystore: Keystore,
navigator: URLNavigatorCoordinator = URLNavigatorCoordinator(),
navigationController: NavigationController = NavigationController()
) {
self.navigationController = navigationController
self.keystore = keystore
self.navigator = navigator
super.init()
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
func start() {
inializers()
migrations()
appTracker.start()
handleNotifications()
applyStyle()
resetToWelcomeScreen()
if keystore.hasWallets {
let wallet = keystore.recentlyUsedWallet ?? keystore.wallets.first!
showTransactions(for: wallet)
} else {
resetToWelcomeScreen()
}
pushNotificationRegistrar.reRegister()
navigator.branch.newEventClosure = { [weak self] event in
guard let coordinator = self?.inCoordinator else { return false }
return coordinator.handleEvent(event)
}
}
func showTransactions(for wallet: WalletInfo) {
let coordinator = InCoordinator(
navigationController: navigationController,
wallet: wallet,
keystore: keystore,
appTracker: appTracker,
navigator: navigator.navigator
)
coordinator.delegate = self
coordinator.start()
addCoordinator(coordinator)
// Activate last event on first sign in
guard let event = navigator.branch.lastEvent else { return }
coordinator.handleEvent(event)
navigator.branch.clearEvents()
}
func inializers() {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).compactMap { URL(fileURLWithPath: $0) }
paths.append(keystore.keysDirectory)
let initializers: [Initializer] = [
SkipBackupFilesInitializer(paths: paths),
]
initializers.forEach { $0.perform() }
//We should clean passcode if there is no wallets. This step is required for app reinstall.
if !keystore.hasWallets {
lock.clear()
}
}
private func migrations() {
let multiCoinCigration = MultiCoinMigration(keystore: keystore, appTracker: appTracker)
let run = multiCoinCigration.start()
if run {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.showMigrationMessage()
}
}
}
private func showMigrationMessage() {
let alertController = UIAlertController(
title: "Great News! Big Update! 🚀",
message: "We have made a huge progress towards supporting and simplifying management of your tokens across blockchains. \n\nTake a look on how to create Multi-Coin Wallet in Trust!",
preferredStyle: UIAlertControllerStyle.alert
)
alertController.popoverPresentationController?.sourceView = self.navigationController.view
alertController.addAction(
UIAlertAction(
title: R.string.localizable.learnMore(),
style: UIAlertActionStyle.default,
handler: { [weak self] _ in
let url = URL(string: "https://medium.com/p/fa50f258274b")
self?.inCoordinator?.showTab(.browser(openURL: url))
}
)
)
navigationController.present(alertController, animated: true, completion: nil)
}
func handleNotifications() {
UIApplication.shared.applicationIconBadgeNumber = 0
}
func resetToWelcomeScreen() {
navigationController.setNavigationBarHidden(true, animated: false)
navigationController.viewControllers = [welcomeViewController]
}
@objc func reset() {
lock.deletePasscode()
pushNotificationRegistrar.unregister()
coordinators.removeAll()
CookiesStore.delete()
navigationController.dismiss(animated: true, completion: nil)
navigationController.viewControllers.removeAll()
resetToWelcomeScreen()
}
func didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: Data) {
pushNotificationRegistrar.didRegister(
with: deviceToken,
networks: networks(for: keystore.wallets)
)
}
private func networks(for wallets: [WalletInfo]) -> [Int: [String]] {
var result: [Int: [String]] = [:]
wallets.forEach { wallet in
for account in wallet.accounts {
guard let coin = account.coin else { break }
var elements: [String] = result[coin.rawValue] ?? []
elements.append(account.address.description)
result[coin.rawValue] = elements
}
}
return result
}
func showInitialWalletCoordinator(entryPoint: WalletEntryPoint) {
let coordinator = InitialWalletCreationCoordinator(
navigationController: navigationController,
keystore: keystore,
entryPoint: entryPoint
)
coordinator.delegate = self
coordinator.start()
addCoordinator(coordinator)
}
}
extension AppCoordinator: WelcomeViewControllerDelegate {
func didPressCreateWallet(in viewController: WelcomeViewController) {
showInitialWalletCoordinator(entryPoint: .createInstantWallet)
}
func didPressImportWallet(in viewController: WelcomeViewController) {
showInitialWalletCoordinator(entryPoint: .importWallet)
}
}
extension AppCoordinator: InitialWalletCreationCoordinatorDelegate {
func didCancel(in coordinator: InitialWalletCreationCoordinator) {
coordinator.navigationController.dismiss(animated: true, completion: nil)
removeCoordinator(coordinator)
}
func didAddAccount(_ account: WalletInfo, in coordinator: InitialWalletCreationCoordinator) {
coordinator.navigationController.dismiss(animated: true, completion: nil)
removeCoordinator(coordinator)
showTransactions(for: account)
}
}
extension AppCoordinator: InCoordinatorDelegate {
func didCancel(in coordinator: InCoordinator) {
removeCoordinator(coordinator)
pushNotificationRegistrar.reRegister()
reset()
}
func didUpdateAccounts(in coordinator: InCoordinator) {
pushNotificationRegistrar.reRegister()
}
}
|
gpl-3.0
|
1ffce4edadf96ae4e58d42229a91599a
| 34.081731 | 194 | 0.659723 | 5.511329 | false | false | false | false |
roambotics/swift
|
test/Reflection/conformance_descriptors.swift
|
2
|
1801
|
// UNSUPPORTED: OS=windows-msvc
// Temporarily disable on AArch64 Linux (rdar://88451721)
// UNSUPPORTED: OS=linux-gnu && CPU=aarch64
// rdar://100558042
// UNSUPPORTED: CPU=arm64e
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift %S/Inputs/Conformances.swift -parse-as-library -emit-module -emit-library -module-name ConformanceCheck -o %t/Conformances
// RUN: %target-swift-reflection-dump %t/Conformances %platform-module-dir/%target-library-name(swiftCore) | %FileCheck %s
// CHECK: CONFORMANCES:
// CHECK: =============
// CHECK-DAG: 16ConformanceCheck10SomeStructV6${{[0-9a-f]*}}yXZ0c6NestedD06${{[0-9a-f]*}}LLV (ConformanceCheck.SomeStruct.(unknown context at ${{[0-9a-f]*}}).(SomeNestedStruct in ${{[0-9a-f]*}})) : ConformanceCheck.MyProto
// CHECK-DAG: 16ConformanceCheck3fooV3barV3bazV3quxV4quuxV5corgeV6graultV6garplyV5waldoV4fredV5plughV5xyzzyV4thudV18SomeConformingTypeV (ConformanceCheck.foo.bar.baz.qux.quux.corge.grault.garply.waldo.fred.plugh.xyzzy.thud.SomeConformingType) : ConformanceCheck.MyProto
// CHECK-DAG: 16ConformanceCheck7StructAV (ConformanceCheck.StructA) : ConformanceCheck.MyProto, Swift.Hashable, Swift.Equatable
// CHECK-DAG: 16ConformanceCheck2E4O (ConformanceCheck.E4) : ConformanceCheck.P1, ConformanceCheck.P2, ConformanceCheck.P3
// CHECK-DAG: 16ConformanceCheck2C4V (ConformanceCheck.C4) : ConformanceCheck.P1, ConformanceCheck.P2
// CHECK-DAG: 16ConformanceCheck2S4V (ConformanceCheck.S4) : ConformanceCheck.P1, ConformanceCheck.P2
// CHECK-DAG: 16ConformanceCheck2C1C (ConformanceCheck.C1) : ConformanceCheck.ClassBoundP
// CHECK-DAG: 16ConformanceCheck3fooV (ConformanceCheck.foo) : ConformanceCheck.MyProto
|
apache-2.0
|
2bec2d32ea5996fb8f3aa76a5ecae54d
| 77.304348 | 287 | 0.789006 | 3.181979 | false | false | false | false |
samburnstone/SwiftStudyGroup
|
Swift Language Guide Playgrounds/StructFun.playground/Pages/Matrix.xcplaygroundpage/Contents.swift
|
1
|
2059
|
//: How about something a tiny bit more complicated - a 2*2 matrix?
struct Matrix: CustomStringConvertible {
struct Dimensions {
let rows: Int
let columns: Int
}
let dimensions: Dimensions
private var grid = [Double]()
init?(topRow: [Double], bottomRow: [Double]) {
dimensions = Dimensions(rows: 2, columns: 2)
guard topRow.count == dimensions.columns && bottomRow.count == dimensions.columns else { return nil }
grid = topRow + bottomRow;
}
var description: String {
get {
return "\(self[0, 0]) \(self[0, 1])\n\(self[1, 0]) \(self[1, 1])"
}
}
subscript(row: Int, column: Int) -> Double {
get {
return grid[indexOfItemAtRow(row, column: column)]
}
set {
grid[indexOfItemAtRow(row, column: column)] = newValue
}
}
private func indexOfItemAtRow(row: Int, column: Int) -> Int {
return row * dimensions.columns + column
}
}
//: Now let's override some operators
func *(scalar: Int, matrix: Matrix) -> Matrix {
// We want to be able to pass in a constant matrix, so we need to copy the contents
// into a mutable variable
var copy = matrix
copy.grid.enumerate()
for (index, _) in copy.grid.enumerate() {
copy.grid[index] = copy.grid[index] * Double(scalar)
}
return copy
}
func *(matrix: Matrix, scalar: Int) -> Matrix {
// We've defined Int * Matrix, so we can just use that method, rather than duplicating it
return scalar * matrix
}
//: Test it!
if let matrix = Matrix(topRow: [0], bottomRow: [10, 5]) {
print("Not nil")
}
else {
print("Returns nil")
}
if let matrix = Matrix(topRow: [0, 10], bottomRow: [10]) {
print("Not nil")
}
else {
print("Returns nil")
}
if let matrix = Matrix(topRow: [10, 5], bottomRow: [20, 30]) {
print(matrix)
// Multiple that Matrix
let multipledMatrix = 5 * matrix
print(multipledMatrix)
}
|
mit
|
70e45927d789e6b1833ff5440b7078f5
| 23.223529 | 109 | 0.578436 | 3.899621 | false | false | false | false |
stephencelis/SQLite.swift
|
Tests/SQLiteTests/Extensions/FTSIntegrationTests.swift
|
1
|
2275
|
import XCTest
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif os(Linux)
import CSQLite
#else
import SQLite3
#endif
@testable import SQLite
class FTSIntegrationTests: SQLiteTestCase {
let email = Expression<String>("email")
let index = VirtualTable("index")
private func createIndex() throws {
try createOrSkip { db in
try db.run(index.create(.FTS5(
FTS5Config()
.column(email)
.tokenizer(.Unicode61()))
))
}
for user in try db.prepare(users) {
try db.run(index.insert(email <- user[email]))
}
}
private func createTrigramIndex() throws {
try createOrSkip { db in
try db.run(index.create(.FTS5(
FTS5Config()
.column(email)
.tokenizer(.Trigram(caseSensitive: false)))
))
}
for user in try db.prepare(users) {
try db.run(index.insert(email <- user[email]))
}
}
override func setUpWithError() throws {
try super.setUpWithError()
try createUsersTable()
try insertUsers("John", "Paul", "George", "Ringo")
}
func testMatch() throws {
try createIndex()
let matches = Array(try db.prepare(index.match("Paul")))
XCTAssertEqual(matches.map { $0[email ]}, ["[email protected]"])
}
func testMatchPartial() throws {
try insertUsers("Paula")
try createIndex()
let matches = Array(try db.prepare(index.match("Pa*")))
XCTAssertEqual(matches.map { $0[email ]}, ["[email protected]", "[email protected]"])
}
func testTrigramIndex() throws {
try createTrigramIndex()
let matches = Array(try db.prepare(index.match("Paul")))
XCTAssertEqual(1, matches.count)
}
private func createOrSkip(_ createIndex: (Connection) throws -> Void) throws {
do {
try createIndex(db)
} catch let error as Result {
try XCTSkipIf(error.description.starts(with: "no such module:") ||
error.description.starts(with: "parse error")
)
throw error
}
}
}
|
mit
|
0f6986be541938b25288db740b40f2b6
| 27.4375 | 92 | 0.570989 | 4.341603 | false | true | false | false |
PlutoMa/EmployeeCard
|
EmployeeCard/EmployeeCard/Core/MapVC/MapVC.swift
|
1
|
2018
|
//
// MapVC.swift
// EmployeeCard
//
// Created by PlutoMa on 2017/4/7.
// Copyright © 2017年 PlutoMa. All rights reserved.
//
import UIKit
class MapVC: UIViewController {
@IBOutlet weak var whiteBlackOffsetX: NSLayoutConstraint!
@IBOutlet weak var buttonScroll: UIScrollView!
@IBOutlet weak var imageScroll: UIScrollView!
@IBOutlet var buttons: [UIButton]!
@IBOutlet var imageViews: [UIImageView]!
override func viewDidLoad() {
super.viewDidLoad()
imageScroll.delegate = self
for imageView in imageViews {
let i = imageViews.index(of: imageView)!
imageView.kf.setImage(with: URL(string: "\(baseUrl)\(mapInfoUrl)floor_\(i).jpg"))
}
}
@IBAction func buttonAction(_ sender: Any) {
let button = sender as! UIView
let tag = button.tag - 11110
//按钮ScrollView偏移设置
var buttonOffsetX = button.plt_midX - buttonScroll.plt_width / 2.0
if buttonOffsetX < 0 {
buttonOffsetX = 0
}
if buttonOffsetX > buttonScroll.plt_width / 2.0 {
buttonOffsetX = buttonScroll.plt_width / 2.0
}
buttonScroll.setContentOffset(CGPoint(x: buttonOffsetX, y: 0), animated: true)
//图片ScrollView偏移设置
imageScroll.setContentOffset(CGPoint(x: imageScroll.plt_width * CGFloat(tag), y: 0), animated: true)
//白条位置设置
whiteBlackOffsetX.constant = button.plt_x
UIView.animate(withDuration: 0.25) {
self.buttonScroll.layoutIfNeeded()
}
}
@IBAction func backAction(_ sender: Any) {
_ = navigationController?.popViewController(animated: true)
}
}
extension MapVC: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == imageScroll {
let i = Int((imageScroll.plt_offsetX + 5) / imageScroll.plt_width)
buttonAction(buttons[i])
}
}
}
|
mit
|
49cc4c0885b1d80b82d6ab9fef6c7cd6
| 30.412698 | 108 | 0.626579 | 4.237687 | false | false | false | false |
zjjzmw1/robot
|
robot/Pods/ObjectMapper/Sources/Mapper.swift
|
49
|
14359
|
//
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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
public enum MappingType {
case fromJSON
case toJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: BaseMappable> {
public var context: MapContext?
public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set.
public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){
self.context = context
self.shouldIncludeNilValues = shouldIncludeNilValues
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSONObject: Any?, toObject object: N) -> N {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSON: [String: Any], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSONObject: Any?) -> N? {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSON: [String: Any]) -> N? {
let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable
if var object = klass.objectForMapping(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? Mappable.Type { // Check if object is Mappable
if var object = klass.init(map: map) as? N {
object.mapping(map: map)
return object
}
} else if N.self is ImmutableMappable.Type { // Check if object is ImmutableMappable
assert(false, "'ImmutableMappable' type requires throwing version of function \(#function) - use 'try' before \(#function)")
} else {
// Ensure BaseMappable is not implemented directly
assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable")
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return [object]
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSONObject: Any?) -> [N]? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapArray(JSONArray: JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String: Any]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String: N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return mapDictionary(JSONObject: parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?) -> [String: N]? {
if let JSON = JSONObject as? [String: [String: Any]] {
return mapDictionary(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? {
// map every value in dictionary to type N
let result = JSON.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] {
if let JSON = JSONObject as? [String : [String : Any]] {
return mapDictionary(JSON: JSON, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in JSON {
if let object = dictionary[key] {
_ = map(JSON: value, toObject: object)
} else {
mutableDictionary[key] = map(JSON: value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? {
if let JSON = JSONObject as? [String: [[String: Any]]] {
return mapDictionaryOfArrays(JSON: JSON)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = JSON.filterMap {
mapArray(JSONArray: $0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? {
if let JSONArray = JSONObject as? [[[String: Any]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(JSONArray: innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization
public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return parsedJSON as? [String: Any]
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSONString: String) -> Any? {
let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let data = data {
let parsedJSON: Any?
do {
parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String, Any>
public func toJSON(_ object: N) -> [String: Any] {
var mutableObject = object
let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return map.JSON
}
///Maps an array of Objects to an array of JSON dictionaries [[String: Any]]
public func toJSONArray(_ array: [N]) -> [[String: Any]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? {
let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: String.Encoding.utf8)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? {
if JSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: Data?
do {
JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSONObject: Any?) -> Set<N>? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapSet(JSONArray: JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String: Any]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]]
public func toJSONSet(_ set: Set<N>) -> [[String: Any]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] {
var mapped = [K: V]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] {
var mapped = [K: [V]]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] {
var mapped = [Key: U]()
for (key, value) in self {
if let newValue = try f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
|
mit
|
a0d8d5d0138ac131a5398e54e0a41f61
| 32.161663 | 145 | 0.699004 | 3.893438 | false | false | false | false |
BjornRuud/HTTPSession
|
Sources/HTTPSession.swift
|
1
|
19219
|
/**
* HTTPSession
*
* Copyright (c) 2017 Bjørn Olav Ruud. Licensed under the MIT license, as follows:
*
* 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
public enum HTTPSessionError: Error, CustomStringConvertible {
case data(Error)
case file(Error)
case http(HTTPURLResponse, Data)
case invalidDownloadURL(URL)
case noResponse
case task(Error)
public var description: String {
switch self {
case .data(let error):
return error.localizedDescription
case .file(let error):
return error.localizedDescription
case .http(let response, let data):
let text: String
if let code = HTTPStatusCode(rawValue: response.statusCode) {
text = code.text
} else {
text = "Unknown"
}
return "\(response.statusCode) \(text) (\(data.count) bytes)"
case .invalidDownloadURL(let url):
return "Invalid download URL: \(url.absoluteString)"
case .noResponse:
return "No response"
case .task(let error):
return error.localizedDescription
}
}
}
public enum HTTPMethod: String {
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
public enum HTTPResult {
case failure(HTTPSessionError)
case success(HTTPURLResponse, Data)
public var error: HTTPSessionError? {
switch self {
case .failure(let error):
return error
case .success(_, _):
return nil
}
}
public var response: HTTPURLResponse? {
switch self {
case .failure(let sessionError):
switch sessionError {
case .http(let response, _):
return response
default:
return nil
}
case .success(let response, _):
return response
}
}
public var data: Data? {
switch self {
case .failure(let sessionError):
switch sessionError {
case .http(_, let data):
return data
default:
return nil
}
case .success(_, let data):
return data
}
}
}
public enum HTTPStatusCode: Int {
case `continue` = 100
case switchingProtocols = 101
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
case multipleChoices = 300
case movedPermanently = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case temporaryRedirect = 307
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 upgradeRequired = 426
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
public var text: String {
switch self {
// 1xx
case .continue: return "Continue"
case .switchingProtocols: return "Switching Protocols"
// 2xx
case .ok: return "OK"
case .created: return "Created"
case .accepted: return "Accepted"
case .nonAuthoritativeInformation: return "Non-Authoritative Information"
case .noContent: return "No Content"
case .resetContent: return "Reset Content"
case .partialContent: return "Partial Content"
// 3xx
case .multipleChoices: return "Multiple Choices"
case .movedPermanently: return "Moved Permanently"
case .found: return "Found"
case .seeOther: return "See Other"
case .notModified: return "Not Modified"
case .useProxy: return "Use Proxy"
case .temporaryRedirect: return "Temporary Redirect"
// 4xx
case .badRequest: return "Bad Request"
case .unauthorized: return "Unauthorized"
case .paymentRequired: return "Payment Required"
case .forbidden: return "Forbidden"
case .notFound: return "Not Found"
case .methodNotAllowed: return "Method Not Allowed"
case .notAcceptable: return "Not Acceptable"
case .proxyAuthenticationRequired: return "Proxy Authentication Required"
case .requestTimeout: return "Request Timeout"
case .conflict: return "Conflict"
case .gone: return "Gone"
case .lengthRequired: return "Length Required"
case .preconditionFailed: return "Precondition Failed"
case .payloadTooLarge: return "Payload Too Large"
case .uriTooLong: return "URI Too Long"
case .unsupportedMediaType: return "Unsupported Media Type"
case .rangeNotSatisfiable: return "Range Not Satisfiable"
case .expectationFailed: return "Expectation Failed"
case .upgradeRequired: return "Upgrade Required"
// 5xx
case .internalServerError: return "Internal Server Error"
case .notImplemented: return "Not Implemented"
case .badGateway: return "Bad Gateway"
case .serviceUnavailable: return "Service Unavailable"
case .gatewayTimeout: return "Gateway Timeout"
case .httpVersionNotSupported: return "HTTP Version Not Supported"
}
}
}
public final class HTTPSession: NSObject {
/// Completion closure for request methods.
public typealias ResultCompletion = (HTTPResult) -> Void
/// Download progress closure called periodically by responses with body data.
public typealias DownloadProgress = (_ bytesDownloaded: Int64, _ totalBytesDownloaded: Int64, _ totalBytesToDownload: Int64) -> Void
/// Upload progress closure called periodically by requests with body data.
public typealias UploadProgress = (_ bytesUploaded: Int64, _ totalBytesUploaded: Int64, _ totalBytesToUpload: Int64) -> Void
/// Shared `HTTPSession` for easy access. The default is configured with `URLSessionConfiguration.default`.
public static var shared = HTTPSession()
/// The underlying `URLSession` used for tasks.
public private(set) var urlSession: URLSession!
/// If set this handler will be used for both session and task authentication challenges.
public var authenticationChallengeHandler: ( (URLSession, URLSessionTask?, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) )?
/// Enable to pass responses directly to the completion handler without parsing the status code.
/// Use this to implement custom response handling.
public var enableResponsePassthrough: Bool = false
/**
Since `HTTPSession` uses the delegate methods on `URLSession`, completion and progress closures (as well as
as other task related data) are stored in a `TaskHandler` object. This dictionary keeps track of the handlers
using the task identifier as key.
*/
fileprivate var taskHandlers = [Int: TaskHandler]()
public init(configuration: URLSessionConfiguration? = nil) {
super.init()
let config = configuration ?? URLSessionConfiguration.default
self.urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}
deinit {
urlSession.invalidateAndCancel()
}
@discardableResult
public func get(_ request: URLRequest, body data: Data = Data(), downloadTo fileUrl: URL? = nil, uploadProgress: UploadProgress? = nil, downloadProgress: DownloadProgress? = nil, completion: @escaping ResultCompletion) -> Int {
return send(request: request, method: HTTPMethod.get.rawValue, body: data, downloadTo: fileUrl, uploadProgress: uploadProgress, downloadProgress: downloadProgress, completion: completion)
}
@discardableResult
public func head(_ request: URLRequest, body data: Data = Data(), uploadProgress: UploadProgress? = nil, completion: @escaping ResultCompletion) -> Int {
return send(request: request, method: HTTPMethod.head.rawValue, body: data, uploadProgress: uploadProgress, completion: completion)
}
@discardableResult
public func post(_ request: URLRequest, body data: Data, downloadTo fileUrl: URL? = nil, uploadProgress: UploadProgress? = nil, downloadProgress: DownloadProgress? = nil, completion: @escaping ResultCompletion) -> Int {
return send(request: request, method: HTTPMethod.post.rawValue, body: data, downloadTo: fileUrl, uploadProgress: uploadProgress, downloadProgress: downloadProgress, completion: completion)
}
@discardableResult
public func put(_ request: URLRequest, body data: Data, downloadTo fileUrl: URL? = nil, uploadProgress: UploadProgress? = nil, downloadProgress: DownloadProgress? = nil, completion: @escaping ResultCompletion) -> Int {
return send(request: request, method: HTTPMethod.put.rawValue, body: data, downloadTo: fileUrl, uploadProgress: uploadProgress, downloadProgress: downloadProgress, completion: completion)
}
@discardableResult
public func delete(_ request: URLRequest, body data: Data = Data(), downloadTo fileUrl: URL? = nil, uploadProgress: UploadProgress? = nil, downloadProgress: DownloadProgress? = nil, completion: @escaping ResultCompletion) -> Int {
return send(request: request, method: HTTPMethod.delete.rawValue, body: data, downloadTo: fileUrl, uploadProgress: uploadProgress, downloadProgress: downloadProgress, completion: completion)
}
@discardableResult
public func send(
request: URLRequest,
method: String = HTTPMethod.get.rawValue,
body data: Data = Data(),
downloadTo fileUrl: URL? = nil,
uploadProgress: UploadProgress? = nil,
downloadProgress: DownloadProgress? = nil,
completion: @escaping ResultCompletion) -> Int
{
if let fileUrl = fileUrl {
var invalidFileUrl = false
if fileUrl.hasDirectoryPath {
invalidFileUrl = true
} else {
// Verify parent folder of file is writeable
let folderUrl = fileUrl.deletingLastPathComponent()
invalidFileUrl = !FileManager.default.isWritableFile(atPath: folderUrl.path)
}
if invalidFileUrl {
urlSession.delegateQueue.addOperation {
completion(.failure(.invalidDownloadURL(fileUrl)))
}
return -1
}
}
var methodRequest = request
methodRequest.httpMethod = method
let task = urlSession.uploadTask(with: methodRequest, from: data)
let handler = TaskHandler(completion: completion)
handler.uploadProgress = uploadProgress
handler.downloadProgress = downloadProgress
handler.url = fileUrl
taskHandlers[task.taskIdentifier] = handler
task.resume()
return task.taskIdentifier
}
}
extension HTTPSession: URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
urlSessionOrTask(session, task: nil, didReceive: challenge, completionHandler: completionHandler)
}
}
extension HTTPSession: URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
urlSessionOrTask(session, task: task, didReceive: challenge, completionHandler: completionHandler)
}
fileprivate func urlSessionOrTask(_ session: URLSession, task: URLSessionTask?, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let authHandler = authenticationChallengeHandler else {
completionHandler(.performDefaultHandling, nil)
return
}
let (disposition, credential) = authHandler(session, task, challenge)
completionHandler(disposition, credential)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard let handler = taskHandlers[task.taskIdentifier], let progress = handler.uploadProgress else {
return
}
progress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let handler = taskHandlers.removeValue(forKey: task.taskIdentifier) else {
return
}
if let error = error {
handler.completion(.failure(.task(error)))
return
}
if let error = handler.error {
handler.completion(.failure(error))
return
}
guard let response = task.response as? HTTPURLResponse else {
handler.completion(.failure(.noResponse))
return
}
let data = handler.data ?? Data()
if !enableResponsePassthrough && 400 ..< 600 ~= response.statusCode {
handler.completion(.failure(.http(response, data)))
} else {
handler.completion(.success(response, data))
}
}
}
extension HTTPSession: URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
// The only data tasks used are upload tasks, and they are converted to download tasks so that we can track progress
completionHandler(.becomeDownload)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
guard let handler = taskHandlers.removeValue(forKey: dataTask.taskIdentifier) else {
return
}
taskHandlers[downloadTask.taskIdentifier] = handler
}
}
extension HTTPSession: URLSessionDownloadDelegate {
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let handler = taskHandlers[downloadTask.taskIdentifier] else {
return
}
var newLocation = location
if let fileUrl = handler.url {
// If download URL is provided, move temp file to requested location
do {
let fm = FileManager.default
try? fm.removeItem(at: fileUrl)
try fm.moveItem(at: location, to: fileUrl)
newLocation = fileUrl
} catch let fileError {
handler.error = .file(fileError)
return
}
}
// Memory map downloaded file to virtual memory so size won't be an issue for returned data.
// If this was a temp file the mapping keeps the file reference alive.
do {
handler.data = try Data(contentsOf: newLocation, options: .alwaysMapped)
} catch let dataError {
handler.error = .data(dataError)
}
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let handler = taskHandlers[downloadTask.taskIdentifier], let progress = handler.downloadProgress else {
return
}
progress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
fileprivate final class TaskHandler {
let completion: HTTPSession.ResultCompletion
var uploadProgress: HTTPSession.UploadProgress? = nil
var downloadProgress: HTTPSession.DownloadProgress? = nil
var data: Data? = nil
var url: URL? = nil
var error: HTTPSessionError? = nil
init(completion: @escaping HTTPSession.ResultCompletion) {
self.completion = completion
}
}
extension URLSession {
public func task(withID taskID: Int, completion: @escaping (URLSessionTask?) -> Void) {
getAllTasks() { (allTasks) in
let foundTask = allTasks.first(where: { $0.taskIdentifier == taskID })
completion(foundTask)
}
}
}
|
mit
|
d06e8be50188644cad3eba3c9cbf0a87
| 40.960699 | 234 | 0.633417 | 5.387721 | false | false | false | false |
Tsiems/mobile-sensing-apps
|
AirDrummer/KDDragAndDropManager.swift
|
1
|
9443
|
//
// KDDragAndDropManager.swift
// KDDragAndDropCollectionViews
//
// Created by Michael Michailidis on 10/04/2015.
// Copyright (c) 2015 Karmadust. All rights reserved.
//
import UIKit
@objc protocol KDDraggable {
func canDragAtPoint(point : CGPoint) -> Bool
func representationImageAtPoint(point : CGPoint) -> UIView?
func dataItemAtPoint(point : CGPoint) -> AnyObject?
func dragDataItem(item : AnyObject) -> Void
@objc optional func startDraggingAtPoint(point : CGPoint) -> Void
@objc optional func stopDragging() -> Void
}
@objc protocol KDDroppable {
func canDropAtRect(rect : CGRect) -> Bool
func willMoveItem(item : AnyObject, inRect rect : CGRect) -> Void
func didMoveItem(item : AnyObject, inRect rect : CGRect) -> Void
func didMoveOutItem(item : AnyObject) -> Void
func dropDataItem(item : AnyObject, atRect : CGRect) -> Void
}
class KDDragAndDropManager: NSObject, UIGestureRecognizerDelegate {
private var canvas : UIView = UIView()
private var views : [UIView] = []
private var longPressGestureRecogniser = UILongPressGestureRecognizer()
struct Bundle {
var offset : CGPoint = CGPoint.zero
var sourceDraggableView : UIView
var overDroppableView : UIView?
var representationImageView : UIView
var dataItem : AnyObject
}
var bundle : Bundle?
init(canvas : UIView, collectionViews : [UIView]) {
super.init()
self.canvas = canvas
self.longPressGestureRecogniser.delegate = self
self.longPressGestureRecogniser.minimumPressDuration = 0.01
self.longPressGestureRecogniser.addTarget(self, action: #selector(KDDragAndDropManager.updateForLongPress))
self.canvas.addGestureRecognizer(self.longPressGestureRecogniser)
self.views = collectionViews
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
for view in self.views.filter({ v -> Bool in v is KDDraggable}) {
let draggable = view as! KDDraggable
let touchPointInView = touch.location(in: view)
if draggable.canDragAtPoint(point: touchPointInView) == true {
if let representation = draggable.representationImageAtPoint(point: touchPointInView) {
representation.frame = self.canvas.convert(representation.frame, from: view)
representation.alpha = 0.7
let pointOnCanvas = touch.location(in: self.canvas)
let offset = CGPoint(x: pointOnCanvas.x - representation.frame.origin.x, y: pointOnCanvas.y - representation.frame.origin.y)
if let dataItem : AnyObject = draggable.dataItemAtPoint(point: touchPointInView) {
self.bundle = Bundle(
offset: offset,
sourceDraggableView: view,
overDroppableView : view is KDDroppable ? view : nil,
representationImageView: representation,
dataItem : dataItem
)
return true
} // if let dataIte...
} // if let representation = dragg...
} // if draggable.canDragAtP...
} // for view in self.views.fil...
return false
}
func updateForLongPress(recogniser : UILongPressGestureRecognizer) -> Void {
if let bundl = self.bundle {
let pointOnCanvas = recogniser.location(in: recogniser.view)
let sourceDraggable : KDDraggable = bundl.sourceDraggableView as! KDDraggable
let pointOnSourceDraggable = recogniser.location(in: bundl.sourceDraggableView)
switch recogniser.state {
case .began :
self.canvas.addSubview(bundl.representationImageView)
sourceDraggable.startDraggingAtPoint?(point: pointOnSourceDraggable)
case .changed :
// Update the frame of the representation image
var repImgFrame = bundl.representationImageView.frame
repImgFrame.origin = CGPoint(x: pointOnCanvas.x - bundl.offset.x, y: pointOnCanvas.y - bundl.offset.y);
bundl.representationImageView.frame = repImgFrame
var overlappingArea : CGFloat = 0.0
var mainOverView : UIView?
for view in self.views.filter({ v -> Bool in v is KDDroppable }) {
let viewFrameOnCanvas = self.convertRectToCanvas(rect: view.frame, fromView: view)
/* ┌────────┐ ┌────────────┐
* │ ┌┼───│Intersection│
* │ ││ └────────────┘
* │ ▼───┘│
* ████████████████│████████│████████████████
* ████████████████└────────┘████████████████
* ██████████████████████████████████████████
*/
let intersectionNew = bundl.representationImageView.frame.intersection(viewFrameOnCanvas).size
if (intersectionNew.width * intersectionNew.height) > overlappingArea {
overlappingArea = intersectionNew.width * intersectionNew.width
mainOverView = view
}
}
if let droppable = mainOverView as? KDDroppable {
let rect = self.canvas.convert(bundl.representationImageView.frame, to: mainOverView)
if droppable.canDropAtRect(rect: rect) {
if mainOverView != bundl.overDroppableView { // if it is the first time we are entering
(bundl.overDroppableView as! KDDroppable).didMoveOutItem(item: bundl.dataItem)
droppable.willMoveItem(item: bundl.dataItem, inRect: rect)
}
// set the view the dragged element is over
self.bundle!.overDroppableView = mainOverView
droppable.didMoveItem(item: bundl.dataItem, inRect: rect)
}
}
case .ended :
if bundl.sourceDraggableView != bundl.overDroppableView { // if we are actually dropping over a new view.
print("\(bundl.overDroppableView?.tag)")
if let droppable = bundl.overDroppableView as? KDDroppable {
sourceDraggable.dragDataItem(item: bundl.dataItem)
let rect = self.canvas.convert(bundl.representationImageView.frame, to: bundl.overDroppableView)
droppable.dropDataItem(item: bundl.dataItem, atRect: rect)
}
}
bundl.representationImageView.removeFromSuperview()
sourceDraggable.stopDragging?()
default:
break
}
} // if let bundl = self.bundle ...
}
// MARK: Helper Methods
func convertRectToCanvas(rect : CGRect, fromView view : UIView) -> CGRect {
var r : CGRect = rect
var v = view
while v != self.canvas {
if let sv = v.superview {
r.origin.x += sv.frame.origin.x
r.origin.y += sv.frame.origin.y
v = sv
continue
}
break
}
return r
}
}
|
mit
|
1a61ae686f554020432722c6ac3647dd
| 36.209016 | 144 | 0.469325 | 5.872574 | false | false | false | false |
dduan/swift
|
stdlib/public/core/OptionSet.swift
|
1
|
6324
|
//===--- OptionSet.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Supplies convenient conformance to `SetAlgebra` for any type
/// whose `RawValue` is a `BitwiseOperations`. For example:
///
/// struct PackagingOptions : OptionSet {
/// let rawValue: Int
/// init(rawValue: Int) { self.rawValue = rawValue }
///
/// static let box = PackagingOptions(rawValue: 1)
/// static let carton = PackagingOptions(rawValue: 2)
/// static let bag = PackagingOptions(rawValue: 4)
/// static let satchel = PackagingOptions(rawValue: 8)
/// static let boxOrBag: PackagingOptions = [box, bag]
/// static let boxOrCartonOrBag: PackagingOptions = [box, carton, bag]
/// }
///
/// In the example above, `PackagingOptions.Element` is the same type
/// as `PackagingOptions`, and instance `a` subsumes instance `b` if
/// and only if `a.rawValue & b.rawValue == b.rawValue`.
public protocol OptionSet : SetAlgebra, RawRepresentable {
// We can't constrain the associated Element type to be the same as
// Self, but we can do almost as well with a default and a
// constrained extension
/// An `OptionSet`'s `Element` type is normally `Self`.
associatedtype Element = Self
// FIXME: This initializer should just be the failable init from
// RawRepresentable. Unfortunately, current language limitations
// that prevent non-failable initializers from forwarding to
// failable ones would prevent us from generating the non-failing
// default (zero-argument) initializer. Since OptionSet's main
// purpose is to create convenient conformances to SetAlgebra,
// we opt for a non-failable initializer.
/// Convert from a value of `RawValue`, succeeding unconditionally.
init(rawValue: RawValue)
}
/// `OptionSet` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet {
/// Returns the set of elements contained in `self`, in `other`, or in
/// both `self` and `other`.
@warn_unused_result
public func union(other: Self) -> Self {
var r: Self = Self(rawValue: self.rawValue)
r.unionInPlace(other)
return r
}
/// Returns the set of elements contained in both `self` and `other`.
@warn_unused_result
public func intersect(other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.intersectInPlace(other)
return r
}
/// Returns the set of elements contained in `self` or in `other`,
/// but not in both `self` and `other`.
@warn_unused_result
public func exclusiveOr(other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.exclusiveOrInPlace(other)
return r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `Element == Self`, which is the default.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where Element == Self {
/// Returns `true` if `self` contains `member`.
///
/// - Equivalent to `self.intersect([member]) == [member]`
@warn_unused_result
public func contains(member: Self) -> Bool {
return self.isSupersetOf(member)
}
/// If `member` is not already contained in `self`, insert it.
///
/// - Equivalent to `self.unionInPlace([member])`
/// - Postcondition: `self.contains(member)`
public mutating func insert(member: Element) {
self.unionInPlace(member)
}
/// If `member` is contained in `self`, remove and return it.
/// Otherwise, return `nil`.
///
/// - Postcondition: `self.intersect([member]).isEmpty`
public mutating func remove(member: Element) -> Element? {
let r = isSupersetOf(member) ? Optional(member) : nil
self.subtractInPlace(member)
return r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `RawValue` conforms to `BitwiseOperations`,
/// which is the usual case. Each distinct bit of an option set's
/// `.rawValue` corresponds to a disjoint element of the option set.
///
/// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s
/// - `intersection` is implemented as a bitwise "and" (`|`) of `rawValue`s
/// - `exclusiveOr` is implemented as a bitwise "exclusive or" (`^`) of `rawValue`s
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where RawValue : BitwiseOperations {
/// Create an empty instance.
///
/// - Equivalent to `[] as Self`
public init() {
self.init(rawValue: .allZeros)
}
/// Insert all elements of `other` into `self`.
///
/// - Equivalent to replacing `self` with `self.union(other)`.
/// - Postcondition: `self.isSupersetOf(other)`
public mutating func unionInPlace(other: Self) {
self = Self(rawValue: self.rawValue | other.rawValue)
}
/// Remove all elements of `self` that are not also present in
/// `other`.
///
/// - Equivalent to replacing `self` with `self.intersect(other)`
/// - Postcondition: `self.isSubsetOf(other)`
public mutating func intersectInPlace(other: Self) {
self = Self(rawValue: self.rawValue & other.rawValue)
}
/// Replace `self` with a set containing all elements contained in
/// either `self` or `other`, but not both.
///
/// - Equivalent to replacing `self` with `self.exclusiveOr(other)`
public mutating func exclusiveOrInPlace(other: Self) {
self = Self(rawValue: self.rawValue ^ other.rawValue)
}
}
@available(*, unavailable, renamed: "OptionSet")
public typealias OptionSetType = OptionSet
|
apache-2.0
|
525a012a153c5b6ea5e80a44e92bd85f
| 36.868263 | 83 | 0.671252 | 4.18254 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/UIControlCell/TimeZoneCustomView.swift
|
1
|
2253
|
//
// TimeZoneView.swift
// Yona
//
// Created by Ben Smith on 12/07/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class TimeZoneCustomView: UIView {
var spreadX : CGFloat = 0
var spreadWidth : CGFloat?
var spreadHeight : CGFloat = 20
var timeZoneColour : UIColor?
var animated : Bool?
override init(frame: CGRect) {
super.init(frame: frame)
spreadX = frame.origin.x
spreadWidth = frame.size.width
backgroundColor = timeZoneColour
}
init(frame: CGRect, colour: UIColor) { // for using CustomView in code
super.init(frame: frame)
spreadX = frame.origin.x
spreadWidth = frame.size.width
timeZoneColour = colour
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func rightAlign (_ spreadValue: Int, spreadCells : [Int], pxPerMinute: CGFloat, pxPerSpread: CGFloat){
//right align
if (spreadValue + 1) < spreadCells.count && (spreadValue - 1) >= 0 { ///don't go out of bounds
if spreadCells[spreadValue + 1] == 15 //if next cell is full
&& spreadCells[spreadValue] < 15 //And current cell is less than 15
&& spreadCells[spreadValue] > 0 { //and great than 0
spreadX = (CGFloat(spreadValue) * pxPerSpread) + (pxPerSpread - (CGFloat(spreadCells[spreadValue]) * pxPerMinute)) //then align to right
} else if spreadCells[spreadValue - 1] == 15 //if previous cell is full
&& spreadCells[spreadValue] < 15 //And current cell is less than 15
&& spreadCells[spreadValue] > 0 { //and great than 0
spreadX = CGFloat(spreadValue) * pxPerSpread //align to left
} else { //else centre align
spreadX = (CGFloat(spreadValue) * pxPerSpread) + (pxPerSpread/2 - spreadWidth!/2) //align in center
}
} else {
spreadX = CGFloat(spreadValue) * pxPerSpread
}
// YOU must set the calculated frame and the backgroundcolor
frame = CGRect(x: spreadX, y: 0, width: spreadWidth!, height: spreadHeight)
backgroundColor = timeZoneColour
//print (self)
}
}
|
mpl-2.0
|
edcb0860262fc298b1bd9971bd674338
| 36.533333 | 152 | 0.607904 | 4.154982 | false | false | false | false |
nagyistoce/Swift-String-Tools
|
StringExtensions.swift
|
1
|
9551
|
//
// String Tools.swift
// Swift String Tools
//
// Created by Jamal Kharrat on 8/11/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension String {
//MARK: helper methods
/**
Returns the length of the string.
:returns: Int length of the string.
*/
var length: Int {
return countElements(self)
}
var objcLength: Int {
return self.utf16Count
}
//MARK: - Linguistics
/**
Returns the langauge of a String
NOTE: String has to be at least 4 characters, otherwise the method will return nil.
:returns: String! Returns a string representing the langague of the string (e.g. en, fr, or und for undefined).
*/
func detectLanguage() -> String! {
if self.length > 4 {
var token : dispatch_once_t = 0
var tagger : NSLinguisticTagger?
dispatch_once(&token) {
tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeLanguage], options: 0)
}
tagger?.string = self
return tagger?.tagAtIndex(0, scheme: NSLinguisticTagSchemeLanguage, tokenRange: nil, sentenceRange: nil)
}
return nil
}
/**
Check the text direction of a given String.
NOTE: String has to be at least 4 characters, otherwise the method will return false.
:returns: Bool The Bool will return true if the string was writting in a right to left langague (e.g. Arabic, Hebrew)
*/
func isRightToLeft() -> Bool {
let language = self.detectLanguage()
return (language? == "ar" || language? == "he")
}
//MARK: - Usablity & Social
/**
Check that a String is only made of white spaces, and new line characters.
:returns: Bool
*/
func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).length == 0
}
/**
Checks if a string is a valid email address using NSDataDetector.
:returns: Bool
*/
var isValidEmail: Bool {
let dataDetector = NSDataDetector(types: NSTextCheckingType.Link.toRaw(), error: nil),
firstMatch = dataDetector.firstMatchInString(self, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, self.length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.URL?.scheme == "mailto")
}
/**
Check that a String is 'tweetable' can be used in a tweet.
:returns: Bool
*/
func isTweetable() -> Bool {
let tweetLength = 140,
// Each link takes 23 characters in a tweet (assuming all links are https).
linksLength = self.getLinks().count * 23,
remaining = tweetLength - linksLength
if linksLength != 0 {
return remaining < 0
} else {
return !(self.utf16Count > tweetLength || self.utf16Count == 0 || self.isOnlyEmptySpacesAndNewLineCharacters())
}
}
/**
Gets an array of Strings for all links found in a String
:returns: [String]
*/
func getLinks() -> [String] {
let error: NSErrorPointer = NSErrorPointer(),
detector = NSDataDetector(types: NSTextCheckingType.Link.toRaw(), error: error),
links = detector.matchesInString(self, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, self.utf16Count)) as [NSTextCheckingResult]
return links.filter { link in
return link.URL != nil
}.map { link -> String in
return link.URL!.absoluteString!
}
}
/**
Gets an array of URLs for all links found in a String
:returns: [NSURL]
*/
func getURLs() -> [NSURL] {
let error: NSErrorPointer = NSErrorPointer(),
detector: NSDataDetector = NSDataDetector(types: NSTextCheckingType.Link.toRaw(), error: error),
links = detector.matchesInString(self, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, self.utf16Count)) as [NSTextCheckingResult]
return links.filter { link in
return link.URL != nil
}.map { link -> NSURL in
return link.URL!
}
}
/**
Gets an array of dates for all dates found in a String
:returns: [NSDate]
*/
func getDates() -> [NSDate] {
let error: NSErrorPointer = NSErrorPointer(),
detector: NSDataDetector = NSDataDetector(types: NSTextCheckingType.Date.toRaw(), error: error),
links = detector.matchesInString(self, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, self.utf16Count)) as [NSTextCheckingResult]
return links.filter { link in
return link.date != nil
}.map { link -> NSDate in
return link.date!
}
}
/**
Gets an array of strings (hashtags #acme) for all links found in a String
:returns: [String]
*/
func getHashtags() -> [String] {
let hashtagDetector = NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpressionOptions.CaseInsensitive, error: nil),
results = hashtagDetector.matchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, self.utf16Count)) as [NSTextCheckingResult]
return results.map { textCheckingResult -> String in
return self[textCheckingResult.rangeAtIndex(0)]
}
}
/**
Gets an array of distinct strings (hashtags #acme) for all hashtags found in a String
:returns: [String]
*/
func getUniqueHashtags() -> [String] {
return NSSet(array: self.getHashtags()).allObjects as [String]
}
/**
Gets an array of strings (mentions @apple) for all mentions found in a String
:returns: [String]
*/
func getMentions() -> [String] {
let mentionDetector = NSRegularExpression(pattern: "@(\\w+)", options: NSRegularExpressionOptions.CaseInsensitive, error: nil),
results = mentionDetector.matchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, self.utf16Count)) as [NSTextCheckingResult]
return results.map { textCheckingResult -> String in
return self[textCheckingResult.rangeAtIndex(0)]
}
}
/**
Check if a String contains a Date in it.
:returns: Bool with true value if it does
*/
func containsDate() -> Bool {
return self.getDates().count > 0
}
/**
Check if a String contains a link in it.
:returns: Bool with true value if it does
*/
func containsLink() -> Bool {
return self.getLinks().count > 0
}
/**
:returns: Base64 encoded string
*/
func encodeToBase64Encoding() -> String {
let utf8str = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
base64EncodedString = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
return base64EncodedString
}
/**
:returns: Decoded Base64 string
*/
func decodeFromBase64Encoding() -> String {
let base64data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions.fromRaw(0)!),
decodedString = NSString(data: base64data, encoding: NSUTF8StringEncoding)
return decodedString
}
/**
Float value from a string
*/
var floatValue: Float {
return (self as NSString).floatValue
}
// MARK: Subscript Methods
subscript (i: Int) -> String {
return String(Array(self)[i])
}
subscript (r: Range<Int>) -> String {
var start = advance(startIndex, r.startIndex),
end = advance(startIndex, r.endIndex)
return substringWithRange(Range(start: start, end: end))
}
subscript (range: NSRange) -> String {
let end = range.location + range.length
return self[Range(start: range.location, end: end)]
}
subscript (substring: String) -> Range<String.Index>? {
return rangeOfString(substring, options: NSStringCompareOptions.LiteralSearch, range: Range(start: startIndex, end: endIndex), locale: NSLocale.currentLocale())
}
}
|
mit
|
83ff958b03440f55423a657156b70f3a
| 33.110714 | 176 | 0.634384 | 4.81644 | false | false | false | false |
0416354917/FeedMeIOS
|
LoginViewController.swift
|
1
|
3900
|
//
// LoginViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 9/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var loginStatus: Bool = false
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.
}
func displayMessage(message: String) {
let alert = UIAlertController(title: "Message", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func closeButtonClicked(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func signInButtonClicked(sender: UIButton) {
NSLog("username: %@, password: %@", usernameTextField.text!, passwordTextField.text!)
let hashPassword = Security.md5(string: passwordTextField.text!)
NSLog("hash password: %@", hashPassword)
let urlString: String = FeedMe.Path.TEXT_HOST + "users/login?email=\(usernameTextField.text!)&pwd=\(hashPassword)"
validateUserLogin(urlString)
}
func validateUserLogin(urlString: String) {
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(myData, response, error) in
if myData != nil {
let dataAsString = NSString(data: myData!, encoding: NSUTF8StringEncoding)
NSLog("data: %@", dataAsString!)
}
if response != nil {
NSLog("response: %@", response!)
}
dispatch_async(dispatch_get_main_queue(), {
let json: NSDictionary
do {
json = try NSJSONSerialization.JSONObjectWithData(myData!, options: .AllowFragments) as! NSDictionary
if let statusInfo = json["statusInfo"] as? String {
if statusInfo == "Y" {
NSLog("Login Success!")
self.loginStatus = true
FeedMe.user = User(email: self.usernameTextField.text!, password: self.passwordTextField.text!)
// set the global user id here:
// FeedMe.Variable.userID =
FeedMe.Variable.userInLoginState = true
self.dismissViewControllerAnimated(true, completion: nil)
} else {
NSLog("Login Fail!")
self.displayMessage("Incorrect email address or password!")
}
}
} catch _ {
}
})
}
task.resume()
}
@IBAction func forgetPasswordButtonClicked(sender: UIButton) {
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
bsd-3-clause
|
1b6ca57dcdd669e4b99e04795e6dafd1
| 32.612069 | 123 | 0.561682 | 5.708638 | false | false | false | false |
Geor9eLau/WorkHelper
|
WorkoutHelper/RecordTableViewCell.swift
|
1
|
1096
|
//
// RecordTableViewCell.swift
// WorkoutHelper
//
// Created by George on 2017/2/13.
// Copyright © 2017年 George. All rights reserved.
//
import UIKit
class RecordTableViewCell: UITableViewCell {
@IBOutlet weak var numberLbl: UILabel!
@IBOutlet weak var weightLbl: UILabel!
@IBOutlet weak var repeatsLbl: UILabel!
@IBOutlet weak var timeLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
numberLbl.layer.borderWidth = 1.0
numberLbl.layer.borderColor = UIColor.black.cgColor
weightLbl.layer.borderWidth = 1.0
weightLbl.layer.borderColor = UIColor.black.cgColor
repeatsLbl.layer.borderWidth = 1.0
repeatsLbl.layer.borderColor = UIColor.black.cgColor
timeLbl.layer.borderWidth = 1.0
timeLbl.layer.borderColor = UIColor.black.cgColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
5a22fdc9eac83220af7cba379d0b43e1
| 26.325 | 65 | 0.671546 | 4.407258 | false | false | false | false |
ilyahal/VKMusic
|
VkPlaylist/GetFriends.swift
|
1
|
4464
|
//
// GetFriends.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/// Получение списка друзей
class GetFriends: RequestManagerObject {
override func performRequest(parameters: [Argument : AnyObject], withCompletionHandler completion: (Bool) -> Void) {
super.performRequest(parameters, withCompletionHandler: completion)
// Отмена выполнения предыдущего запроса и удаление загруженной информации
cancel()
DataManager.sharedInstance.friends.clear()
// Если нет подключения к интернету
if !Reachability.isConnectedToNetwork() {
state = .NotSearchedYet
error = .NetworkError
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
completion(false)
return
}
// Слушатель для уведомления об успешном завершении получения друзей
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerDidGetFriendsNotification, object: nil, queue: NSOperationQueue.mainQueue()) { notification in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
let result = notification.userInfo!["Friends"] as! [Friend]
DataManager.sharedInstance.friends.saveNewArray(result)
self.state = DataManager.sharedInstance.friends.array.count == 0 ? .NoResults : .Results
self.error = .None
completion(true)
}
// Слушатель для получения уведомления об ошибке при подключении к интернету
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetFriendsNetworkErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
DataManager.sharedInstance.friends.clear()
self.state = .NotSearchedYet
self.error = .NetworkError
completion(false)
}
// Слушатель для уведомления о других ошибках
NSNotificationCenter.defaultCenter().addObserverForName(VKAPIManagerGetFriendsErrorNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in
self.removeActivState() // Удаление состояние выполнения запроса
// Сохранение данных
DataManager.sharedInstance.friends.clear()
self.state = .NotSearchedYet
self.error = .UnknownError
completion(false)
}
let request = VKAPIManager.friendsGet()
state = .Loading
error = .None
RequestManager.sharedInstance.activeRequests[key] = request
}
}
|
mit
|
821d6303542179a34afc935c1b93657d
| 39.43 | 170 | 0.65908 | 4.86988 | false | false | false | false |
bumrush/PhotoUploader
|
PhotoUploader/PhotoUploaderViewController.swift
|
2
|
5476
|
//
// PhotoUploaderViewController.swift
// PhotoUploader
//
// Created by Justin Cano on 4/22/15.
// Copyright (c) 2015 bumrush. All rights reserved.
//
import UIKit
import MobileCoreServices
import AssetsLibrary
class PhotoUploaderViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
var cognitoIdentityId: String?
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
cognitoIdentityId = appDelegate.cognitoIdentityId
println("\(cognitoIdentityId!)")
}
// MARK: - UI Methods
@IBAction func viewPhotosFromAWS(sender: UIButton) {
let downloadingFilePath = NSTemporaryDirectory().stringByAppendingPathComponent("downloaded-object")
let downloadingFileURL = NSURL.fileURLWithPath(downloadingFilePath)
let request: AWSS3TransferManagerDownloadRequest = AWSS3TransferManagerDownloadRequest()
request.bucket = S3BucketName
request.key = "users/\(cognitoIdentityId!)/test-object"
request.downloadingFileURL = downloadingFileURL
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.download(request).continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock: { [unowned self] (task) -> AnyObject! in
if task.error != nil {
println("\(task.error)")
} else {
if let downloadOutput = task.result as? AWSS3TransferManagerDownloadOutput {
let myCIImage = CIImage(contentsOfURL: downloadOutput.body as! NSURL)
let image = UIImage(CIImage: myCIImage)
self.imageView.image = image
self.updateUI()
println("\(downloadOutput.body)")
}
}
return nil
})
let listOjbectsOutput: AWSS3ListObjectsOutput = AWSS3ListObjectsOutput()
var objectSummaries = listOjbectsOutput.contents
println("\(objectSummaries)")
}
@IBAction func choosePhoto(sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
if let availableTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary) {
picker.mediaTypes = [kUTTypeImage]
picker.delegate = self
//picker.allowsEditing = true
presentViewController(picker, animated: true, completion: nil)
}
}
}
private func updateUI() {
makeRoomForImage()
}
// MARK: - Image
var imageView = UIImageView()
@IBOutlet weak var imageViewContainer: UIView! {
didSet {
imageViewContainer.addSubview(imageView)
}
}
// MARK: - Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject] ) {
var image = info[UIImagePickerControllerEditedImage] as? UIImage
if image == nil {
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
//process image
imageView.image = image
makeRoomForImage()
//save image to app's temp folder
let path = NSTemporaryDirectory().stringByAppendingPathComponent("upload-image.tmp")
let imageData = UIImagePNGRepresentation(image)
imageData.writeToFile(path, atomically: true)
let imageURL = NSURL(fileURLWithPath: path)
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.bucket = S3BucketName
uploadRequest.key = "users/\(cognitoIdentityId!)/test-object"
uploadRequest.body = imageURL
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock: { (task) -> AnyObject! in
if task.error != nil {
println("\(task.error)")
println("Error uploading: \(imageURL)")
} else {
println("Upload completed!")
}
return nil
})
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Helper Methods
func makeRoomForImage() {
var extraHeight:CGFloat = 0
if imageView.image?.aspectRatio > 0 {
if let width = imageView.superview?.frame.size.width {
let height = width / imageView.image!.aspectRatio
extraHeight = height - imageView.frame.height
imageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
}
} else {
extraHeight = -imageView.frame.height
imageView.frame = CGRectZero
}
preferredContentSize = CGSize(width: preferredContentSize.width, height: preferredContentSize.height + extraHeight)
}
}
extension UIImage {
var aspectRatio:CGFloat {
return size.height != 0 ? size.width / size.height : 0
}
}
|
mit
|
e86f76ae601253c806dd97c536af1c38
| 36.506849 | 147 | 0.636961 | 5.674611 | false | false | false | false |
LucianoPolit/RepositoryKit
|
Example/Source/User.swift
|
1
|
3114
|
//
// User.swift
// Example
//
// Created by Luciano Polit on 20/7/16.
// Copyright © 2016 Luciano Polit. All rights reserved.
//
import RepositoryKit
import Foundation
import CoreData
/*
It needs to conform:
- RKNetworkingStorageEntity: it allows to be used as a `Networking entity` and a `Storage entity`.
- RKPatchable: it allows to be used to make PATCH requests.
*/
class User: NSManagedObject, NetworkingStorageEntity, Patchable {
// MARK: - Properties
// It is changed to print some cleaner code.
override var description: String {
return "\(id) - \(firstName!) - \(lastName!) - \(synchronized!)"
}
// Avoid showing the entire id.
var shortID: String {
if id.count > 2 {
return String(id![id.index(id.endIndex, offsetBy: -3)...])
} else {
return id
}
}
// It represents the entity with a dictionary.
var dictionary: [String: Any] {
return [
"_id": id,
"firstName": firstName!,
"lastName": lastName!
]
}
// It save a copy of the last representation on the `Networking Repository Store`.
var dictionaryMemory: [String: Any] = [:]
// MARK: - Initializers
override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
// When an MO is inserted by a FRC, it is initialized by this way.
// So we need to save a dictionary representation.
// It will allow us to make patch requests from the beginning.
if let _ = id, let _ = firstName, let _ = lastName {
self.dictionaryMemory = self.dictionary
}
}
// Initializes an object with a dictionary.
required convenience init?(dictionary: [String: Any], context: NSManagedObjectContext) {
// Check for our requirements.
guard let entity = NSEntityDescription.entity(forEntityName: "User", in: context),
let firstName = dictionary["firstName"] as? String,
let lastName = dictionary["lastName"] as? String
else { return nil }
// Call the initializer.
self.init(entity: entity, insertInto: context)
// Update the properties.
self.firstName = firstName
self.lastName = lastName
// If it is initialized with an 'id', use it.
if let id = dictionary["_id"] as? String {
self.id = id
} else {
self.id = "-1"
}
// If it is initialized from a `Networking entity`, it is synchronized.
self.synchronized = self.id != "-1" ? 1 : 0
// Update user dictionary
self.dictionaryMemory = self.dictionary
}
// MARK: - Methods
// Updates self with a dictionary.
func update(_ dictionary: [String: Any]) {
synchronized = true
id <~ dictionary["_id"]
firstName <~ dictionary["firstName"]
lastName <~ dictionary["lastName"]
dictionaryMemory = self.dictionary
}
}
|
mit
|
9f114ad0481604a5ca29a6657389f576
| 31.427083 | 102 | 0.595246 | 4.639344 | false | false | false | false |
mojio/mojio-ios-sdk
|
MojioSDK/Models/Trip.swift
|
1
|
3243
|
//
// Trip.swift
// MojioSDK
//
// Created by Ashish Agarwal on 2016-02-10.
// Copyright © 2016 Mojio. All rights reserved.
//
import UIKit
import Foundation
import ObjectMapper
public class Trip: Mappable {
public dynamic var VehicleId : String? = nil
public dynamic var Name : String? = nil
public var Tags : [String] = []
public dynamic var MojioId : String? = nil
public dynamic var Completed : Bool = false
public dynamic var TripDuration : String? = nil
public var TripDistance : Distance? = nil
public dynamic var StartTimestamp : String? = nil
public dynamic var EndTimestamp : String? = nil
public var StartOdometer : Odometer? = nil
public var EndOdometer : Odometer? = nil
public var StartLocation : Location? = nil
public var EndLocation : Location? = nil
public var MaxSpeed : Speed? = nil
public var MaxRPM : RPM? = nil
public var MaxAcceleration : Acceleration? = nil
public var MaxDeceleration : Acceleration? = nil
public var TripFuelEfficiency : FuelEfficiency? = nil
public var StartFuelLevel : FuelLevel? = nil
public var EndFuelLevel : FuelLevel? = nil
public var IdlingCount : Int? = nil
public var HarshAccelCount : Int? = nil
public var HarshDecelCount : Int? = nil
public dynamic var Id : String? = nil
public dynamic var CreatedOn : String? = nil
public dynamic var LastModified : String? = nil
public required convenience init?(_ map: Map) {
self.init()
}
public required init() {
}
public static func primaryKey() -> String? {
return "Id"
}
public func json() -> String? {
let dictionary : NSMutableDictionary = NSMutableDictionary()
if self.Name != nil {
dictionary.setObject(self.Name!, forKey: "Name")
}
let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
return NSString(data: data, encoding: NSUTF8StringEncoding)! as String
}
public func mapping(map: Map) {
VehicleId <- map["VehicleId"];
Name <- map["Name"];
MojioId <- map["MojioId"];
Completed <- map["Completed"];
TripDuration <- map["Duration"];
TripDistance <- map["Distance"]
StartTimestamp <- map["StartTimestamp"];
EndTimestamp <- map["EndTimestamp"];
StartOdometer <- map["StartOdometer"];
EndOdometer <- map["EndOdometer"];
StartLocation <- map["StartLocation"];
EndLocation <- map["EndLocation"];
MaxSpeed <- map["MaxSpeed"];
MaxRPM <- map["MaxRPM"];
MaxAcceleration <- map["MaxAcceleration"];
MaxDeceleration <- map["MaxDeceleration"];
TripFuelEfficiency <- map["FuelEfficiency"];
StartFuelLevel <- map["StartFuelLevel"];
EndFuelLevel <- map["EndFuelLevel"];
IdlingCount <- map["IdlingCount"];
HarshAccelCount <- map["HarshAcclCount"];
HarshDecelCount <- map["HarshDecelCount"];
Id <- map["Id"];
CreatedOn <- map["CreatedOn"];
LastModified <- map["LastModified"];
Tags <- map["Tags"]
}
}
|
mit
|
2611d968bff0b2969dd05e124761f859
| 33.489362 | 120 | 0.624306 | 4.435021 | false | false | false | false |
rechsteiner/Parchment
|
Parchment/Structs/PagingDiff.swift
|
1
|
2147
|
import Foundation
struct PagingDiff {
private let from: PagingItems
private let to: PagingItems
private var fromCache: [Int: PagingItem]
private var toCache: [Int: PagingItem]
private var lastMatchingItem: PagingItem?
init(from: PagingItems, to: PagingItems) {
self.from = from
self.to = to
fromCache = [:]
toCache = [:]
for item in from.items {
fromCache[item.identifier] = item
}
for item in to.items {
toCache[item.identifier] = item
}
for toItem in to.items {
for fromItem in from.items {
if toItem.isEqual(to: fromItem) {
lastMatchingItem = toItem
break
}
}
}
}
func removed() -> [IndexPath] {
let removed = diff(visibleItems: from, cache: toCache)
var items: [IndexPath] = []
if let lastItem = lastMatchingItem {
for indexPath in removed {
if let lastIndexPath = from.indexPath(for: lastItem) {
if indexPath.item < lastIndexPath.item {
items.append(indexPath)
}
}
}
}
return items
}
func added() -> [IndexPath] {
let removedCount = removed().count
let added = diff(visibleItems: to, cache: fromCache)
var items: [IndexPath] = []
if let lastItem = lastMatchingItem {
for indexPath in added {
if let lastIndexPath = from.indexPath(for: lastItem) {
if indexPath.item + removedCount <= lastIndexPath.item {
items.append(indexPath)
}
}
}
}
return items
}
private func diff(visibleItems: PagingItems, cache: [Int: PagingItem]) -> [IndexPath] {
return visibleItems.items.compactMap { item in
if cache[item.identifier] == nil {
return visibleItems.indexPath(for: item)
}
return nil
}
}
}
|
mit
|
a7727356a614f0bd98a981b62c3a581a
| 26.525641 | 91 | 0.51048 | 4.993023 | false | false | false | false |
jdspoone/Recipinator
|
RecipeBook/StepViewController.swift
|
1
|
8491
|
/*
Written by Jeff Spooner
*/
import UIKit
import CoreData
class StepViewController: BaseViewController, NSFetchedResultsControllerDelegate
{
var step: Step
var completion: ((Step) -> Void)?
let imageSortingBlock: (Image, Image) -> Bool = { $0.index < $1.index }
var summaryTextField: UITextField!
var detailTextView: UITextView!
var imagesFetchedResultsController: NSFetchedResultsController<Image>!
var imagePreviewPageViewController: ImagePreviewPageViewController!
init(step: Step, editing: Bool, context: NSManagedObjectContext, completion: ((Step) -> Void)? = nil)
{
self.step = step
self.completion = completion
super.init(editing: editing, context: context)
}
func restoreState()
{
summaryTextField.text = step.summary
detailTextView.text = step.detail
}
// MARK: - UIViewController
required init?(coder aDecoder: NSCoder)
{ fatalError("init(coder:) has not been implemented") }
override func loadView()
{
super.loadView()
// Configure the summary text field
summaryTextField = UITextField(frame: CGRect.zero)
summaryTextField.font = UIFont(name: "Helvetica", size: 16)
summaryTextField.placeholder = NSLocalizedString("SUMMARY", comment: "")
summaryTextField.textAlignment = .center
summaryTextField.returnKeyType = .done
summaryTextField.translatesAutoresizingMaskIntoConstraints = false
summaryTextField.delegate = self
addSubviewToScrollView(summaryTextField)
// Configure the detail text view
detailTextView = UITextView(frame: CGRect.zero)
detailTextView.font = UIFont(name: "Helvetica", size: 16)
detailTextView.layer.cornerRadius = 5.0
detailTextView.layer.borderWidth = 0.5
detailTextView.layer.borderColor = UIColor.lightGray.cgColor
detailTextView.translatesAutoresizingMaskIntoConstraints = false
detailTextView.delegate = self
addSubviewToScrollView(detailTextView)
// Configure the image preview page view controller
imagePreviewPageViewController = ImagePreviewPageViewController(images: step.images)
addChildViewController(imagePreviewPageViewController)
imagePreviewPageViewController.didMove(toParentViewController: self)
let imagePreview = imagePreviewPageViewController.view!
imagePreview.translatesAutoresizingMaskIntoConstraints = false
addSubviewToScrollView(imagePreview)
// Configure the layout bindings for the summary text field
summaryTextField.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -16.0).isActive = true
summaryTextField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
summaryTextField.heightAnchor.constraint(equalToConstant: 30.0).isActive = true
summaryTextField.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 8.0).isActive = true
// Configure the layout bindings for the detail text view
detailTextView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -16.0).isActive = true
detailTextView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
detailTextView.heightAnchor.constraint(equalToConstant: 150).isActive = true
detailTextView.topAnchor.constraint(equalTo: summaryTextField.bottomAnchor, constant: 8.0).isActive = true
// Configure the layout bindings for the image view
let sideLength: CGFloat = UIDevice.current.userInterfaceIdiom == .phone ? 320.0 : 640.0
imagePreview.widthAnchor.constraint(equalToConstant: sideLength).isActive = true
imagePreview.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
imagePreview.heightAnchor.constraint(equalToConstant: sideLength).isActive = true
imagePreview.topAnchor.constraint(equalTo: detailTextView.bottomAnchor, constant: 8.0).isActive = true
}
override func viewDidLoad()
{
super.viewDidLoad()
// Configure the images fetch request
let imagesFetchRequest = NSFetchRequest<Image>(entityName: "Image")
imagesFetchRequest.sortDescriptors = [NSSortDescriptor(key: "index", ascending: true)]
imagesFetchRequest.predicate = NSPredicate(format: "%K == %@", argumentArray: ["stepUsedIn", step.objectID])
// Configure the images fetched results controller
imagesFetchedResultsController = NSFetchedResultsController(fetchRequest: imagesFetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
imagesFetchedResultsController.delegate = self
// Attempt to fetch the images associated with this step
do { try imagesFetchedResultsController.performFetch() }
catch let e { fatalError("error: \(e)") }
// Set the title of the navigation item
navigationItem.title = NSLocalizedString("STEP", comment: "") + " \(step.number + 1)"
// Configure a gesture recognizer on the image preview view controller
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.selectImage(_:)))
imagePreviewPageViewController.view!.addGestureRecognizer(gestureRecognizer)
restoreState()
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
// Update the content size of the scroll view
updateScrollViewContentSize()
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
// Register custom notifications
observations = [
Observation(source: self, keypaths: ["editing"], options: .initial, block:
{ (changes: [NSKeyValueChangeKey : Any]?) -> Void in
self.summaryTextField.isUserInteractionEnabled = self.isEditing
self.summaryTextField.borderStyle = self.isEditing ? .roundedRect : .none
self.detailTextView.isEditable = self.isEditing
})
]
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
// If we're moving from the parentViewController, end editing and call the completion callback
if isMovingFromParentViewController {
endEditing(self)
completion?(step)
}
}
// MARK: - NSFetchedResultsControllerDelegate
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
{
// Update the image preview view controller
imagePreviewPageViewController.updateImages(newImages: step.images)
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true;
}
override func textFieldDidEndEditing(_ textField: UITextField)
{
step.summary = textField.text!
super.textFieldDidEndEditing(textField)
}
// MARK: - UITextViewDelegate
func textViewShouldEndEditing(_ textView: UITextView) -> Bool
{
textView.resignFirstResponder()
return true
}
override func textViewDidEndEditing(_ textView: UITextView)
{
step.detail = textView.text!
super.textViewDidEndEditing(textView)
}
// MARK: - Actions
func selectImage(_ sender: AnyObject?)
{
// Ensure the active subview resigns as first responder
activeSubview?.resignFirstResponder()
// If we're editing, or if the recipe has no images
if isEditing || step.images.count == 0 {
// Configure and show an ImageCollectionViewController
let imageCollectionViewController = ImageCollectionViewController(images: step.images, imageOwner: step, editing: true, context: managedObjectContext)
show(imageCollectionViewController, sender: self)
}
// Otherwise, show an ImagePageViewController
else {
let imagePageViewController = ImagePageViewController(images: step.images, index: imagePreviewPageViewController.currentIndex!)
show(imagePageViewController, sender: self)
}
}
}
|
mit
|
b1f9d427d18613073fb89b5318538df8
| 36.078603 | 198 | 0.69768 | 5.706317 | false | false | false | false |
loganSims/wsdot-ios-app
|
wsdot/SimpleMapViewController.swift
|
1
|
1737
|
//
// SimpleMapViewController.swift
// WSDOT
//
// Copyright (c) 2018 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import UIKit
import CoreLocation
import GoogleMaps
class SimpleMapViewController: UIViewController {
weak var markerDelegate: MapMarkerDelegate? = nil
weak var mapDelegate: GMSMapViewDelegate? = nil
deinit {
if let mapView = view as? GMSMapView{
mapView.clear()
mapView.delegate = nil
}
view.removeFromSuperview()
markerDelegate = nil
mapDelegate = nil
}
override func loadView() {
super.loadView()
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 0))
MapThemeUtils.setMapStyle(mapView, traitCollection)
mapView.isTrafficEnabled = true
mapView.delegate = mapDelegate
view = mapView
if let parent = markerDelegate {
parent.mapReady()
}
}
}
|
gpl-3.0
|
08a12584da5cb252d1b602e6a6b61195
| 28.948276 | 134 | 0.657455 | 4.73297 | false | false | false | false |
zSher/BulletThief
|
BulletThief/BulletThief/AIManager.swift
|
1
|
10440
|
//
// AIManager.swift
// BulletThief
//
// Created by Zachary on 5/18/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import UIKit
import SpriteKit
enum AIState {
case Idle
case ReadyToSpawn
case Spawning
case StrafeSpawn
}
///Class to manage spawning / difficulty
class AIManager: NSObject {
var scene:GameScene!
var state:AIState = AIState.ReadyToSpawn
var difficulty:CGFloat = 0
var goldNode:SKSpriteNode!
var difficultyFlag: (low:CGFloat, high:CGFloat) = (25, 100)
let STRAFE_CHANCE: CGFloat = 0.75
//Timing variables
var timeSinceSpawn:CFTimeInterval = 0
var goldSpawnCoolDownMax = 10
var goldCoolDown:CFTimeInterval = 0
let GOLD_CD_RANGE:CGFloat = 3
//MARK: - Init -
init(scene:GameScene){
self.scene = scene
super.init()
self.createGoldBody()
self.setGoldCoolDown()
}
//MARK: - Update -
func update(deltaTime: CFTimeInterval) {
updateDifficulty();
spawnGold(deltaTime)
spawnEnemies()
}
//MARK: - Gold Spawn Methods -
func spawnGold(deltaTime: CFTimeInterval) {
if timeSinceSpawn >= goldCoolDown {
spawnGoldAtRandomLocation()
self.setGoldCoolDown()
timeSinceSpawn = 0
} else {
timeSinceSpawn += deltaTime
}
}
//Set the cooldown of gold spawn to a
func setGoldCoolDown(){
goldCoolDown = CFTimeInterval(randomRange(CGFloat(goldSpawnCoolDownMax) - GOLD_CD_RANGE, CGFloat(goldSpawnCoolDownMax) + GOLD_CD_RANGE))
}
//MARK: - Spawn Enemies Methods -
func spawnEnemies(){
if self.state == AIState.ReadyToSpawn {
var chance = randomRange(0, 1)
if chance < STRAFE_CHANCE {
self.state = .StrafeSpawn
} else {
self.state = .Spawning
}
} else if self.state == .StrafeSpawn {
//Spawn quickly on a increasing x, or decreasing x
var numberToSpawn = 0
if difficulty < difficultyFlag.low {
numberToSpawn = 3
} else if difficulty >= difficultyFlag.low && difficulty < difficultyFlag.high {
numberToSpawn = 4
} else {
numberToSpawn = 5 + Int((difficulty - difficultyFlag.high) / difficultyFlag.high) //add 1 every 100 difficulty
}
strafeSpawn(numberToSpawn)
self.state = .Idle
} else if self.state == .Spawning {
//Basic random Spawn
if difficulty < difficultyFlag.low {
println("easy")
easySpawn()
self.state = .Idle
} else if difficulty >= difficultyFlag.low && difficulty < difficultyFlag.high {
println("medium")
mediumSpawn()
self.state = .Idle
} else {
println("hard")
hardSpawn()
self.state = .Idle
}
} else if self.state == .Idle {
//Wait for spawn to finish
}
}
//MARK: - Basic Spawn Difficulties -
func easySpawn(){
var spawnDelay = SKAction.waitForDuration(4, withRange: 2)
var spawnBlock = SKAction.runBlock(){
self.spawnEnemyAtRandomLocation(Enemy())
}
var spawnSequence = SKAction.sequence([spawnBlock, spawnDelay])
var spawner = SKAction.repeatAction(spawnSequence, count: Int(randomRange(5, 8)))
var resetBlock = SKAction.runBlock() { self.resetToReady() }
scene.runAction(SKAction.sequence([spawner, resetBlock]))
}
//Spawns enemies faster with higher chance of harder enemies
func mediumSpawn(){
var spawnDelay = SKAction.waitForDuration(3, withRange: 2.5)
var spawnBlock = SKAction.runBlock(){
var chance = randomRange(0, 1)
if chance < 0.10 {
self.spawnEnemyAtRandomLocation(GoldDashEnemy())
} else if chance >= 0.10 && chance < 0.3 {
self.spawnEnemyAtRandomLocation(WaveEnemy())
} else if chance >= 0.3 && chance < 0.7 {
self.spawnEnemyAtRandomLocation(SplitShotEnemy())
} else {
self.spawnEnemyAtRandomLocation(Enemy())
}
}
var spawnSequence = SKAction.sequence([spawnBlock, spawnDelay])
var spawner = SKAction.repeatAction(spawnSequence, count: Int(randomRange(7, 10)))
var resetBlock = SKAction.runBlock() { self.resetToReady() }
scene.runAction(SKAction.sequence([spawner, resetBlock]))
}
//Spawns enemies even faster then medium and at even faster speeds
func hardSpawn(){
var spawnDelay = SKAction.waitForDuration(1, withRange: 0.75)
var spawnBlock = SKAction.runBlock(){
var chance = randomRange(0, 1)
if chance < 0.10 {
self.spawnEnemyAtRandomLocation(GoldDashEnemy())
} else if chance >= 0.10 && chance < 0.4 {
self.spawnEnemyAtRandomLocation(WaveEnemy())
} else if chance >= 0.4 && chance < 0.8 {
self.spawnEnemyAtRandomLocation(SplitShotEnemy())
} else {
self.spawnEnemyAtRandomLocation(Enemy())
}
}
var spawnSequence = SKAction.sequence([spawnBlock, spawnDelay])
var spawner = SKAction.repeatAction(spawnSequence, count: Int(randomRange(2, 4)))
var resetBlock = SKAction.runBlock() { self.resetToReady() }
scene.runAction(SKAction.sequence([spawner, resetBlock]))
}
//MARK: - Strafe -
//Spawn enemies in a wave
func strafeSpawn(numberToSpawn:Int){
//Choose enemy type
var chance = randomRange(0, 1)
var enemyType:Enemy!
if chance < 0.10 {
enemyType = GoldDashEnemy()
} else if chance >= 0.10 && chance < 0.3 {
enemyType = WaveEnemy()
} else if chance >= 0.3 && chance < 0.7 {
enemyType = SplitShotEnemy()
} else {
enemyType = Enemy()
}
//Pick a side to spawn, and set the incr/dec amount
var isLeftSpawn = randomRange(0, 1) >= 0.5
var spawnPosition = createRandomTopPoint(offset: enemyType.size)
var spawnChangeAmount = isLeftSpawn ? enemyType.size.width : -enemyType.size.width
var spawnDelay = SKAction.waitForDuration(0.5)
var spawnBlock = SKAction.runBlock() {
var enemy = enemyType.copy() as Enemy
enemy.position = spawnPosition
//create straight line movement
var enemyPath = self.createStraightLinePath(offset: enemy.size)
enemy.addPath(enemyPath)
var moveAction = SKAction.followPath(enemy.movementPath!.CGPath, asOffset: true, orientToPath: false, speed: enemy.speed)
var removeAction = SKAction.removeFromParent()
var onScreenActionGrp = SKAction.sequence([moveAction, removeAction])
enemy.addToScene(self.scene)
enemy.runAction(onScreenActionGrp)
spawnPosition.x += spawnChangeAmount
}
var sequenceAction = SKAction.sequence([spawnBlock, spawnDelay])
var repeateAction = SKAction.repeatAction(sequenceAction, count: numberToSpawn)
var resetBlock = SKAction.runBlock() { self.resetToReady() }
var strafeFullAction = SKAction.sequence([repeateAction, resetBlock])
scene.runAction(strafeFullAction)
}
//MARK: - Helper Functions-
func updateDifficulty(){
difficulty = scene.distance //TODO: be more smart about difficulty
}
//Reset state to readyToSpawn
func resetToReady(){
self.state = .ReadyToSpawn
}
//Helper to spawn gold at random location
func spawnGoldAtRandomLocation() {
var gold = goldNode.copy() as SKSpriteNode
gold.speed = goldNode.speed //not copied for some reason
gold.position = createRandomTopPoint(offset: gold.size)
//create straight line movement
var path = createStraightLinePath(offset: gold.size)
var moveAction = SKAction.followPath(path.CGPath, asOffset: true, orientToPath: false, speed: gold.speed)
var removeAction = SKAction.removeFromParent()
var onScreenActionGrp = SKAction.sequence([moveAction, removeAction])
scene.addChild(gold)
gold.runAction(onScreenActionGrp)
}
//AI Manager spawns new enemies
func spawnEnemyAtRandomLocation(enemy:Enemy){
enemy.position = createRandomTopPoint(offset: enemy.size)
//create straight line movement
var enemyPath = createStraightLinePath(offset: enemy.size)
enemy.addPath(enemyPath)
enemy.addToScene(scene)
}
//Helper to create line paths for spawning
func createStraightLinePath(offset:CGSize = CGSizeZero) -> UIBezierPath {
//create straight line movement
var path = UIBezierPath()
path.moveToPoint(CGPointZero)
path.addLineToPoint(CGPointMake(0, -scene.size.height - offset.height -
20))
return path
}
//Helper to create random spawn points above top of screen
func createRandomTopPoint(offset: CGSize = CGSizeZero) -> CGPoint {
var xRand = randomRange(0, scene.size.width)
var yPos = scene.size.height + offset.height
return CGPointMake(xRand, yPos)
}
//Create a single gold node to copy from
func createGoldBody(){
var goldTexture = SKTexture(imageNamed: "goldItem")
goldNode = SKSpriteNode(texture: goldTexture, color: UIColor.clearColor(), size: goldTexture.size())
goldNode.physicsBody = SKPhysicsBody(edgeLoopFromRect: goldNode.frame)
goldNode.physicsBody?.dynamic = true
goldNode.physicsBody?.categoryBitMask = CollisionCategories.Gold
goldNode.physicsBody?.contactTestBitMask = CollisionCategories.Player
goldNode.physicsBody?.collisionBitMask = CollisionCategories.None
goldNode.physicsBody?.usesPreciseCollisionDetection = false
goldNode.speed = 10
goldNode.name = "gold"
}
}
|
mit
|
de6ef015e415d676367ed6d31f9b6dd4
| 36.021277 | 144 | 0.606226 | 4.64 | false | false | false | false |
onevcat/APNGKit
|
Demo/Demo-macOS/SamplesViewController.swift
|
1
|
3122
|
//
// ViewController.swift
// Demo-macOS
//
// Created by Wang Wei on 2021/10/31.
//
import Cocoa
import APNGKit
class SamplesViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var imageView: APNGImageView!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var imageSizeLabel: NSTextField!
@IBOutlet weak var imageDurationLabel: NSTextField!
@IBOutlet weak var imageFrameCountLabel: NSTextField!
@IBOutlet weak var infoView: NSStackView!
@IBOutlet weak var previewLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("SampleImageTableCell"), owner: self) as! NSTableCellView
cell.textField?.stringValue = sampleImages[row]
if let url = Bundle.main.url(forResource: sampleImages[row], withExtension: "apng") {
cell.imageView?.image = NSImage(contentsOf: url)
} else {
cell.imageView?.image = NSImage(named: sampleImages[row])
}
return cell
}
func numberOfRows(in tableView: NSTableView) -> Int {
return sampleImages.count
}
func tableViewSelectionDidChange(_ notification: Notification) {
guard tableView.selectedRow >= 0 else { return }
infoView.isHidden = false
previewLabel.isHidden = true
let name = sampleImages[tableView.selectedRow]
do {
let image = try APNGImage(named: name)
imageViewWidthConstraint.constant = image.size.width
imageViewHeightConstraint.constant = image.size.height
imageSizeLabel.stringValue = "\(image.size.width)x\(image.size.height) @ \(Int(image.scale))x"
imageDurationLabel.stringValue = "-"
imageFrameCountLabel.stringValue = "\(image.numberOfFrames)"
image.onFramesInformationPrepared.delegate(on: self) { [weak image] (self, _) in
guard let image = image else { return }
switch image.duration {
case .loadedPartial:
fatalError("All frames should be already loaded.")
case .full(let d):
self.imageDurationLabel.stringValue = String(format: "%.3f", d) + " s"
}
}
imageView.image = image
} catch {
if let i = error.apngError?.normalImage {
imageView.staticImage = i
}
print(error)
}
}
}
|
mit
|
36802024a00c0fb1e1359547bda55bba
| 33.307692 | 141 | 0.610186 | 5.264755 | false | false | false | false |
zavsby/ProjectHelpersSwift
|
Classes/Categories/UIView+Extensions.swift
|
1
|
2245
|
//
// UIView+Extensions.swift
// ProjectHelpers-Swift
//
// Created by Sergey on 02.11.15.
// Copyright © 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
import UIKit
public extension UIView {
//MARK: View frame and dimensions
public var top: Float {
get {
return Float(self.frame.origin.y)
}
set(top) {
var frame = self.frame
frame.origin.y = CGFloat(top)
self.frame = frame
}
}
public var left: Float {
get {
return Float(self.frame.origin.x)
}
set(left) {
var frame = self.frame
frame.origin.x = CGFloat(left)
self.frame = frame
}
}
public var bottom: Float {
get {
return Float(self.frame.origin.y + self.frame.size.height)
}
set(bottom) {
var frame = self.frame
frame.origin.y = CGFloat(bottom) - frame.size.height
self.frame = frame
}
}
public var right: Float {
get {
return Float(self.frame.origin.x + self.frame.size.width)
}
set(right) {
var frame = self.frame
frame.origin.x = CGFloat(right) - frame.size.width
self.frame = frame
}
}
public var height: Float {
get {
return Float(self.frame.size.height)
}
set(height) {
var frame = self.frame
frame.size.height = CGFloat(height)
self.frame = frame
}
}
public var width: Float {
get {
return Float(self.frame.size.width)
}
set(width) {
var frame = self.frame
frame.size.width = CGFloat(width)
self.frame = frame;
}
}
//MARK: Addtional methods
public func screenImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let copiedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return copiedImage
}
}
|
mit
|
b33794480c64fab75bf84fdba98578de
| 23.402174 | 75 | 0.528966 | 4.434783 | false | false | false | false |
JGiola/swift
|
test/SILGen/cf.swift
|
5
|
4597
|
// RUN: %target-swift-emit-silgen -module-name cf -enable-objc-interop -import-cf-types -sdk %S/Inputs %s -o - | %FileCheck %s
import CoreCooling
// CHECK: sil hidden [ossa] @$s2cf8useEmAllyySo16CCMagnetismModelCF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $CCMagnetismModel):
func useEmAll(_ model: CCMagnetismModel) {
// CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply>
let power = CCPowerSupplyGetDefault()
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>>
let unmanagedFridge = CCRefrigeratorCreate(power)
// CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator>
let managedFridge = CCRefrigeratorSpawn(power)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> ()
CCRefrigeratorOpen(managedFridge)
// CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator>
let copy = CCRefrigeratorCopy(managedFridge)
// CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator>
let clone = CCRefrigeratorClone(managedFridge)
// CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> ()
CCRefrigeratorDestroy(clone)
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>?, $@convention(objc_method) (CCMagnetismModel) -> @unowned_inner_pointer Optional<Unmanaged<CCRefrigerator>>
let f0 = model.refrigerator()
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator>
let f1 = model.getRefrigerator()
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator>
let f2 = model.takeRefrigerator()
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator>
let f3 = model.borrowRefrigerator()
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!foreign : (CCMagnetismModel) -> (CCRefrigerator?) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> ()
model.setRefrigerator(copy)
// CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!foreign : (CCMagnetismModel) -> (CCRefrigerator?) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> ()
model.giveRefrigerator(copy)
// rdar://16846555
let prop: CCRefrigerator = model.fridgeProp
}
// Ensure that accessors are emitted for fields used as protocol witnesses.
protocol Impedance {
associatedtype Component
var real: Component { get }
var imag: Component { get }
}
extension CCImpedance: Impedance {}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzvgTW
// CHECK-LABEL: sil shared [transparent] [serialized] [ossa] @$sSo11CCImpedanceV4realSdvg
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzvgTW
// CHECK-LABEL: sil shared [transparent] [serialized] [ossa] @$sSo11CCImpedanceV4imagSdvg
class MyMagnetism : CCMagnetismModel {
// CHECK-LABEL: sil private [thunk] [ossa] @$s2cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator
override func getRefrigerator() -> CCRefrigerator {
return super.getRefrigerator()
}
// CHECK-LABEL: sil private [thunk] [ossa] @$s2cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator
override func takeRefrigerator() -> CCRefrigerator {
return super.takeRefrigerator()
}
// CHECK-LABEL: sil private [thunk] [ossa] @$s2cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator
override func borrowRefrigerator() -> CCRefrigerator {
return super.borrowRefrigerator()
}
}
|
apache-2.0
|
9547b242f0f71c053a095f9a16ddefb9
| 56.4625 | 254 | 0.750925 | 4.104464 | false | false | false | false |
danteteam/KYCircularProgress
|
Source/KYCircularProgress.swift
|
1
|
9277
|
// KYCircularProgress.swift
//
// Copyright (c) 2014-2015 Kengo Yokoyama.
//
// 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
// MARK: - KYCircularProgress
public class KYCircularProgress: UIView {
/**
Typealias of progressChangedClosure.
*/
public typealias progressChangedHandler = (progress: Double, circularView: KYCircularProgress) -> Void
/**
This closure is called when set value to `progress` property.
*/
private var progressChangedClosure: progressChangedHandler?
/**
Main progress view.
*/
private var progressView: KYCircularShapeView!
/**
Gradient mask layer of `progressView`.
*/
private var gradientLayer: CAGradientLayer!
/**
Guide view of `progressView`.
*/
private var progressGuideView: KYCircularShapeView?
/**
Mask layer of `progressGuideView`.
*/
private var guideLayer: CALayer?
/**
Current progress value. (0.0 - 1.0)
*/
@IBInspectable public var progress: Double = 0.0 {
didSet {
let clipProgress = max( min(progress, Double(1.0)), Double(0.0) )
progressView.updateProgress(clipProgress)
progressChangedClosure?(progress: clipProgress, circularView: self)
}
}
/**
Progress start angle.
*/
public var startAngle: Double = 0.0 {
didSet {
progressView.startAngle = startAngle
progressGuideView?.startAngle = startAngle
}
}
/**
Progress end angle.
*/
public var endAngle: Double = 0.0 {
didSet {
progressView.endAngle = endAngle
progressGuideView?.endAngle = endAngle
}
}
/**
Main progress line width.
*/
@IBInspectable public var lineWidth: Double = 8.0 {
didSet {
progressView.shapeLayer().lineWidth = CGFloat(lineWidth)
}
}
/**
Guide progress line width.
*/
@IBInspectable public var guideLineWidth: Double = 8.0 {
didSet {
progressGuideView?.shapeLayer().lineWidth = CGFloat(guideLineWidth)
}
}
/**
Progress bar path. You can create various type of progress bar.
*/
public var path: UIBezierPath? {
didSet {
progressView.shapeLayer().path = path?.CGPath
progressGuideView?.shapeLayer().path = path?.CGPath
}
}
/**
Progress bar colors. You can set many colors in `colors` property, and it makes gradation color in `colors`.
*/
public var colors: [UIColor]? {
didSet {
updateColors(colors)
}
}
/**
Progress guide bar color.
*/
@IBInspectable public var progressGuideColor: UIColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.2) {
didSet {
guideLayer?.backgroundColor = progressGuideColor.CGColor
}
}
/**
Switch of progress guide view. If you set to `true`, progress guide view is enabled.
*/
@IBInspectable public var showProgressGuide: Bool = false {
didSet {
setNeedsLayout()
layoutIfNeeded()
configureProgressGuideLayer(showProgressGuide)
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureProgressLayer()
}
public override init(frame: CGRect) {
super.init(frame: frame)
configureProgressLayer()
}
/**
Create `KYCircularProgress` with progress guide.
:param: frame `KYCircularProgress` frame.
:param: showProgressGuide If you set to `true`, progress guide view is enabled.
*/
public init(frame: CGRect, showProgressGuide: Bool) {
super.init(frame: frame)
configureProgressLayer()
self.showProgressGuide = showProgressGuide
}
/**
This closure is called when set value to `progress` property.
:param: completion progress changed closure.
*/
public func progressChangedClosure(completion: progressChangedHandler) {
progressChangedClosure = completion
}
private func configureProgressLayer() {
progressView = KYCircularShapeView(frame: bounds)
progressView.shapeLayer().fillColor = UIColor.clearColor().CGColor
progressView.shapeLayer().path = path?.CGPath
progressView.shapeLayer().lineWidth = CGFloat(lineWidth)
progressView.shapeLayer().strokeColor = tintColor.CGColor
gradientLayer = CAGradientLayer(layer: layer)
gradientLayer.frame = progressView.frame
gradientLayer.startPoint = CGPointMake(0, 0.5)
gradientLayer.endPoint = CGPointMake(1, 0.5)
gradientLayer.mask = progressView.shapeLayer()
gradientLayer.colors = colors ?? [UIColor(rgba: 0x9ACDE755).CGColor, UIColor(rgba: 0xE7A5C955).CGColor]
layer.addSublayer(gradientLayer)
}
private func configureProgressGuideLayer(showProgressGuide: Bool) {
if showProgressGuide && progressGuideView == nil {
progressGuideView = KYCircularShapeView(frame: bounds)
progressGuideView!.shapeLayer().fillColor = UIColor.clearColor().CGColor
progressGuideView!.shapeLayer().path = progressView.shapeLayer().path
progressGuideView!.shapeLayer().lineWidth = CGFloat(guideLineWidth)
progressGuideView!.shapeLayer().strokeColor = tintColor.CGColor
guideLayer = CAGradientLayer(layer: layer)
guideLayer!.frame = progressGuideView!.frame
guideLayer!.mask = progressGuideView!.shapeLayer()
guideLayer!.backgroundColor = progressGuideColor.CGColor
guideLayer!.zPosition = -1
progressGuideView!.updateProgress(1.0)
layer.addSublayer(guideLayer)
}
}
private func updateColors(colors: [UIColor]?) {
var convertedColors: [CGColorRef] = []
if let colors = colors {
for color in colors {
convertedColors.append(color.CGColor)
}
if convertedColors.count == 1 {
convertedColors.append(convertedColors.first!)
}
} else {
convertedColors = [UIColor(rgba: 0x9ACDE7FF).CGColor, UIColor(rgba: 0xE7A5C9FF).CGColor]
}
gradientLayer.colors = convertedColors
}
}
// MARK: - KYCircularShapeView
class KYCircularShapeView: UIView {
var startAngle = 0.0
var endAngle = 0.0
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
private func shapeLayer() -> CAShapeLayer {
return layer as! CAShapeLayer
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
updateProgress(0)
}
override func layoutSubviews() {
super.layoutSubviews()
if startAngle == endAngle {
endAngle = startAngle + (M_PI * 2)
}
shapeLayer().path = shapeLayer().path ?? layoutPath().CGPath
}
private func layoutPath() -> UIBezierPath {
let halfWidth = CGFloat(CGRectGetWidth(frame) / 2.0)
return UIBezierPath(arcCenter: CGPointMake(halfWidth, halfWidth), radius: halfWidth - shapeLayer().lineWidth, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true)
}
private func updateProgress(progress: Double) {
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
shapeLayer().strokeEnd = CGFloat(progress)
CATransaction.commit()
}
}
// MARK: - UIColor Extension
extension UIColor {
convenience public init(rgba: Int64) {
let red = CGFloat((rgba & 0xFF000000) >> 24) / 255.0
let green = CGFloat((rgba & 0x00FF0000) >> 16) / 255.0
let blue = CGFloat((rgba & 0x0000FF00) >> 8) / 255.0
let alpha = CGFloat( rgba & 0x000000FF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
|
mit
|
582b46db9a577f1bb265740843322eb0
| 31.550877 | 196 | 0.634257 | 4.851987 | false | false | false | false |
dreamsxin/swift
|
test/IRGen/newtype.swift
|
2
|
4466
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype | FileCheck %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t -I %S/../IDE/Inputs/custom-modules) %s -emit-ir -enable-swift-newtype -O | FileCheck %s -check-prefix=OPT
import CoreFoundation
import Foundation
import Newtype
// REQUIRES: objc_interop
// Witness table for synthesized ClosedEnums : _ObjectiveCBridgeable.
// CHECK: @_TWPVSC10ClosedEnums21_ObjectiveCBridgeable7Newtype = linkonce_odr
// CHECK-LABEL: define %CSo8NSString* @_TF7newtype14getErrorDomainFT_VSC11ErrorDomain()
public func getErrorDomain() -> ErrorDomain {
// CHECK: load %CSo8NSString*, %CSo8NSString** getelementptr inbounds (%VSC11ErrorDomain, %VSC11ErrorDomain* {{.*}}@SNTErrOne
return .one
}
// CHECK-LABEL: _TF7newtype6getFooFT_VSC18NSNotificationName
public func getFoo() -> NSNotificationName {
return NSNotificationName.Foo
// CHECK: load {{.*}} @FooNotification
// CHECK: ret
}
// CHECK-LABEL: _TF7newtype21getGlobalNotificationFSiSS
public func getGlobalNotification(_ x: Int) -> String {
switch x {
case 1: return kNotification
// CHECK: load {{.*}} @kNotification
case 2: return Notification
// CHECK: load {{.*}} @Notification
case 3: return swiftNamedNotification
// CHECK: load {{.*}} @kSNNotification
default: return NSNotificationName.bar.rawValue
// CHECK: load {{.*}} @kBarNotification
}
// CHECK: ret
}
// CHECK-LABEL: _TF7newtype17getCFNewTypeValueFT6useVarSb_VSC9CFNewType
public func getCFNewTypeValue(useVar: Bool) -> CFNewType {
if (useVar) {
return CFNewType.MyCFNewTypeValue
// CHECK: load {{.*}} @MyCFNewTypeValue
} else {
return FooAudited()
// CHECK: call {{.*}} @FooAudited()
}
// CHECK: ret
}
// CHECK-LABEL: _TF7newtype21getUnmanagedCFNewTypeFT6useVarSb_GVs9UnmanagedCSo8CFString_
public func getUnmanagedCFNewType(useVar: Bool) -> Unmanaged<CFString> {
if (useVar) {
return CFNewType.MyCFNewTypeValueUnaudited
// CHECK: load {{.*}} @MyCFNewTypeValueUnaudited
} else {
return FooUnaudited()
// CHECK: call {{.*}} @FooUnaudited()
}
// CHECK: ret
}
// Triggers instantiation of ClosedEnum : _ObjectiveCBridgeable
// witness table.
public func hasArrayOfClosedEnums(closed: [ClosedEnum]) {
}
// CHECK-LABEL: _TF7newtype11compareABIsFT_T_
public func compareABIs() {
let new = getMyABINewType()
let old = getMyABIOldType()
takeMyABINewType(new)
takeMyABIOldType(old)
takeMyABINewTypeNonNull(new!)
takeMyABIOldTypeNonNull(old!)
let newNS = getMyABINewTypeNS()
let oldNS = getMyABIOldTypeNS()
takeMyABINewTypeNonNullNS(newNS!)
takeMyABIOldTypeNonNullNS(oldNS!)
// Make sure that the calling conventions align correctly, that is we don't
// have double-indirection or anything else like that
// CHECK: declare %struct.__CFString* @getMyABINewType()
// CHECK: declare %struct.__CFString* @getMyABIOldType()
//
// CHECK: declare void @takeMyABINewType(%struct.__CFString*)
// CHECK: declare void @takeMyABIOldType(%struct.__CFString*)
//
// CHECK: declare void @takeMyABINewTypeNonNull(%struct.__CFString*)
// CHECK: declare void @takeMyABIOldTypeNonNull(%struct.__CFString*)
//
// CHECK: declare %0* @getMyABINewTypeNS()
// CHECK: declare %0* @getMyABIOldTypeNS()
//
// CHECK: declare void @takeMyABINewTypeNonNullNS(%0*)
// CHECK: declare void @takeMyABIOldTypeNonNullNS(%0*)
}
// OPT-LABEL: define i1 @_TF7newtype12compareInitsFT_Sb
public func compareInits() -> Bool {
let mf = MyInt(rawValue: 1)
let mfNoLabel = MyInt(1)
let res = mf.rawValue == MyInt.one.rawValue
&& mfNoLabel.rawValue == MyInt.one.rawValue
// OPT: [[ONE:%.*]] = load i32, i32*{{.*}}@kMyIntOne{{.*}}, align 4
// OPT-NEXT: [[COMP:%.*]] = icmp eq i32 [[ONE]], 1
takesMyInt(mf)
takesMyInt(mfNoLabel)
takesMyInt(MyInt(rawValue: kRawInt))
takesMyInt(MyInt(kRawInt))
// OPT: tail call void @takesMyInt(i32 1)
// OPT-NEXT: tail call void @takesMyInt(i32 1)
// OPT-NEXT: [[RAWINT:%.*]] = load i32, i32*{{.*}} @kRawInt{{.*}}, align 4
// OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]])
// OPT-NEXT: tail call void @takesMyInt(i32 [[RAWINT]])
return res
// OPT-NEXT: ret i1 [[COMP]]
}
// CHECK-LABEL: anchor
// OPT-LABEL: anchor
public func anchor() -> Bool {
return false
}
|
apache-2.0
|
310b77f562d02aa6d1fa0cd6b11b9183
| 32.840909 | 167 | 0.698388 | 3.60452 | false | false | false | false |
ben-ng/swift
|
test/IRGen/lazy_globals.swift
|
4
|
2147
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8
// CHECK: @_Tv12lazy_globals1xSi = hidden global %Si zeroinitializer, align 8
// CHECK: @_Tv12lazy_globals1ySi = hidden global %Si zeroinitializer, align 8
// CHECK: @_Tv12lazy_globals1zSi = hidden global %Si zeroinitializer, align 8
// CHECK: define internal void @globalinit_[[T]]_func0() {{.*}} {
// CHECK: entry:
// CHECK: store i64 1, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1xSi, i32 0, i32 0), align 8
// CHECK: store i64 2, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1ySi, i32 0, i32 0), align 8
// CHECK: store i64 3, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1zSi, i32 0, i32 0), align 8
// CHECK: ret void
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1xSi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1xSi to i8*)
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1ySi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1ySi to i8*)
// CHECK: }
// CHECK: define hidden i8* @_TF12lazy_globalsau1zSi() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1zSi to i8*)
// CHECK: }
var (x, y, z) = (1, 2, 3)
// CHECK: define hidden i64 @_TF12lazy_globals4getXFT_Si() {{.*}} {
// CHECK: entry:
// CHECK: %0 = call i8* @_TF12lazy_globalsau1xSi()
// CHECK: %1 = bitcast i8* %0 to %Si*
// CHECK: %._value = getelementptr inbounds %Si, %Si* %1, i32 0, i32 0
// CHECK: %2 = load i64, i64* %._value, align 8
// CHECK: ret i64 %2
// CHECK: }
func getX() -> Int { return x }
|
apache-2.0
|
0f6806388a8edabd80bd1b2d59c4767c
| 45.673913 | 132 | 0.637168 | 2.843709 | false | false | false | false |
ben-ng/swift
|
test/Generics/function_decls.swift
|
9
|
1407
|
// RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Generic function declarations
//===----------------------------------------------------------------------===//
func f0<T>(x: Int, y: Int, t: T) { }
func f1<T : Any>(x: Int, y: Int, t: T) { }
func f2<T : IteratorProtocol>(x: Int, y: Int, t: T) { }
func f3<T : () -> ()>(x: Int, y: Int, t: T) { } // expected-error{{expected a type name or protocol composition restricting 'T'}}
func f4<T>(x: T, y: T) { }
// Non-protocol type constraints.
func f6<T : Wonka>(x: T) {} // expected-error{{use of undeclared type 'Wonka'}}
// FIXME: The term 'inherit' is unfortunate here.
func f7<T : Int>(x: T) {} // expected-error{{inheritance from non-protocol, non-class type 'Int'}}
func f8<T> (x: Int) {} //expected-error{{generic parameter 'T' is not used in function signature}}
public class A<X> {
init<T>(){} //expected-error{{generic parameter 'T' is not used in function signature}}
public func f9<T, U>(x: T, y: X) {} //expected-error{{generic parameter 'U' is not used in function signature}}
public func f10(x: Int) {}
public func f11<T, U>(x: X, y: T) {} //expected-error{{generic parameter 'U' is not used in function signature}}
}
protocol P { associatedtype A }
func f12<T : P>(x: T) -> T.A<Int> {} //expected-error{{cannot specialize non-generic type 'T.A'}}{{29-34=}}
|
apache-2.0
|
e6d46b33edd8364014c14220f5f6c6c1
| 45.9 | 129 | 0.568586 | 3.272093 | false | false | false | false |
RedRoma/Lexis-Database
|
LexisDatabaseTests/SupplementalInformation+JSONTests.swift
|
1
|
1023
|
//
// SupplementalInformation_JSON.swift
// LexisDatabase
//
// Created by Wellington Moreno on 9/20/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import AlchemyGenerator
import AlchemyTest
import Foundation
import Archeota
@testable import LexisDatabase
class SupplementalInformation_JSONTests: LexisTest
{
var instance: SupplementalInformation!
override func beforeEachTest()
{
super.beforeEachTest()
instance = Generators.randomSupplementalInformation
}
func testAsJSON()
{
let json = instance.asJSON()
XCTAssertFalse(json == nil)
assertThat(json is NSDictionary)
}
func testFromJSON()
{
let json = instance.asJSON()!
let result = SupplementalInformation.fromJSON(json: json)
XCTAssertFalse(result == nil)
assertThat(result is SupplementalInformation)
let copy = result as! SupplementalInformation
assertThat(copy == instance)
}
}
|
apache-2.0
|
59564192baf849479803dd9c45265190
| 22.227273 | 65 | 0.663405 | 4.843602 | false | true | false | false |
mwildeboer/Axis
|
Source/AXContext.swift
|
1
|
6324
|
//
// AXContext.swift
// Axis
//
// Created by Menno Wildeboer on 14/02/16.
// Copyright © 2016 Menno Wideboer. All rights reserved.
//
import Foundation
public class AXContext {
internal var constraints: [ AXLayoutAttribute: AXConstraint ] = [ AXLayoutAttribute: AXConstraint ]()
internal func applyConstraint(c: AXConstraint) {
self.constraints[c.firstAttribute] = c
}
internal func installConstraints() {
if self.constraints.isEmpty {
return
}
let view = self.constraints.values.first!.firstView
var frame = view.frame
/////////////////////////////////////////////////////////////////////////////
// HORIZONTAL
/////////////////////////////////////////////////////////////////////////////
if let c = self.constraints[.Width] {
if c.secondAttribute == .Width {
frame.size.width = CGRectGetWidth(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .Height {
frame.size.width = CGRectGetHeight(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .None {
frame.size.width = c.constant
}
}
if let c = self.constraints[.Left] {
if c.secondAttribute == .Left {
frame.origin.x = CGRectGetMinX(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .Right {
frame.origin.x = CGRectGetMaxX(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .None {
frame.origin.x = c.constant
}
if let c = self.constraints[.Right] {
if self.constraints[.Width] == nil {
if c.secondAttribute == .Right {
frame.size.width = max(0, (CGRectGetMaxX(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetMinX(frame))
} else if (c.secondAttribute == .Left) {
frame.size.width = max(0, (CGRectGetMinX(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetMinX(frame))
} else if c.secondAttribute == .None && c.firstView.superview != nil {
frame.size.width = max(0, (CGRectGetMaxX(c.firstView.superview!.frame) - c.constant) - CGRectGetMinX(frame))
}
}
}
}
else if let c = self.constraints[.Right] {
if c.secondAttribute == .Right {
frame.origin.x = max(0, (CGRectGetMaxX(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetWidth(frame))
} else if (c.secondAttribute == .Left) {
frame.origin.x = (CGRectGetMinX(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetWidth(frame)
} else if c.secondAttribute == .None && c.firstView.superview != nil {
frame.origin.x = CGRectGetWidth(c.firstView.superview!.frame) - c.constant - CGRectGetWidth(frame)
}
}
else if let c = self.constraints[.CenterX] {
if c.secondAttribute == .CenterX {
if (c.secondView! == c.firstView.superview) {
frame.origin.x = (CGRectGetWidth(c.secondView!.bounds)/2 * c.multiplier + c.offset) - CGRectGetWidth(frame)/2
} else {
frame.origin.x = (CGRectGetMidX(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetWidth(frame)/2
}
} else if c.secondAttribute == .None {
frame.origin.x = c.constant - CGRectGetWidth(frame)/2
}
}
/////////////////////////////////////////////////////////////////////////////
// VERTICAL
/////////////////////////////////////////////////////////////////////////////
if let c = self.constraints[.Height] {
if c.secondAttribute == .Width {
frame.size.height = CGRectGetWidth(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .Height {
frame.size.height = CGRectGetHeight(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .None {
frame.size.height = c.constant
}
}
if let c = self.constraints[.Top] {
if c.secondAttribute == .Top {
frame.origin.y = CGRectGetMinY(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .Bottom {
frame.origin.y = CGRectGetMaxY(c.secondView!.frame) * c.multiplier + c.offset
} else if c.secondAttribute == .None {
frame.origin.y = c.constant
}
if let c = self.constraints[.Bottom] {
if self.constraints[.Height] == nil {
if c.secondAttribute == .Bottom {
frame.size.height = max(0, (CGRectGetMaxY(c.secondView!.frame) * c.multiplier - c.offset) - CGRectGetMinY(frame))
} else if (c.secondAttribute == .Left) {
frame.size.height = max(0, (CGRectGetMinY(c.secondView!.frame) * c.multiplier - c.offset) - CGRectGetMinY(frame))
} else if c.secondAttribute == .None && c.firstView.superview != nil {
frame.size.height = max(0, (CGRectGetMaxY(c.firstView.superview!.frame) - c.constant) - CGRectGetMinY(frame))
}
}
}
}
else if let c = self.constraints[.Bottom] {
if c.secondAttribute == .Bottom {
frame.origin.y = max(0, (CGRectGetMaxY(c.secondView!.frame) * c.multiplier - c.offset) - CGRectGetHeight(frame))
} else if (c.secondAttribute == .Left) {
frame.origin.y = (CGRectGetMinY(c.secondView!.frame) * c.multiplier - c.offset) - CGRectGetHeight(frame)
} else if c.secondAttribute == .None && c.firstView.superview != nil {
frame.origin.y = CGRectGetHeight(c.firstView.superview!.frame) - c.constant - CGRectGetHeight(frame)
}
}
else if let c = self.constraints[.CenterY] {
if c.secondAttribute == .CenterY {
if (c.secondView! == c.firstView.superview) {
frame.origin.y = (CGRectGetHeight(c.secondView!.bounds)/2 * c.multiplier + c.offset) - CGRectGetHeight(frame)/2
} else {
frame.origin.y = (CGRectGetMidY(c.secondView!.frame) * c.multiplier + c.offset) - CGRectGetHeight(frame)/2
}
} else if c.secondAttribute == .None {
frame.origin.y = c.constant - CGRectGetHeight(frame)/2
}
}
/////////////////////////////////////////////////////////////////////////////
// APPLY
/////////////////////////////////////////////////////////////////////////////
view.frame = CGRectIntegral(frame)
}
}
|
bsd-2-clause
|
50261b190241bef335492724b5568e2a
| 42.916667 | 125 | 0.571248 | 4.179114 | false | false | false | false |
AzenXu/Memo
|
Memo/Classes/Models/Models.swift
|
1
|
784
|
//
// Knowledge.swift
// Memo
//
// Created by XuAzen on 16/9/15.
// Copyright © 2016年 azen. All rights reserved.
//
import Foundation
import RealmSwift
public class Knowledge: Object {
public dynamic var title: String = ""
public dynamic var desc: String = ""
public dynamic var updateTime: NSTimeInterval = NSDate().timeIntervalSince1970
public dynamic var memoryCount: Int = 0
override public static func primaryKey() -> String? {
return "title"
}
}
public extension KnowledgeBridge {
public func vatting() -> Knowledge {
let knowledge = Knowledge()
knowledge.title = title
knowledge.desc = desc
knowledge.updateTime = updateTime
knowledge.memoryCount = 0
return knowledge
}
}
|
mit
|
75becda9c3119b8ad8bdeee5b550e7c5
| 23.40625 | 82 | 0.65685 | 4.4375 | false | false | false | false |
jejefcgb/ProjetS9-iOS
|
Projet S9/HomeViewController.swift
|
1
|
10095
|
//
// HomeViewController.swift
// Projet S9
//
// Created by Jérémie Foucault on 25/11/2014.
// Copyright (c) 2014 Jérémie Foucault. All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
class HomeViewController: BaseViewController, UIBarPositioningDelegate, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var startDayLabel: UILabel!
@IBOutlet weak var endDayLabel: UILabel!
@IBOutlet weak var conferenceSubView: UIView!
@IBOutlet weak var noConferenceSubView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var calendarSubView: UIView!
//var items: [String] = ["We", "Heart", "Swift"]
var talk = [Talk]()
var after = [Talk]();
var myColor: UIColor = UIColor();
let app:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
override func viewDidLoad() {
super.unwindSegueIdentifier = "homeUnwindSegueToMenu"
super.viewDidLoad()
self.getConferencesFromAPI()
self.getBeaconsFromAPI()
self.getTopologyFromAPI()
self.conferenceSubView.hidden = true
self.calendarSubView.hidden = true
if app.lastBeacons?.count > 0 {
self.updateData()
self.conferenceSubView.hidden = false
self.noConferenceSubView.hidden = true
self.calendarSubView.hidden = false
myColor = getRandomColor();
self.newFindClosestDates();
self.tableView.reloadData();
}
//let myConference: Conference = Conference.sharedInstance
//println(myConference.tracks?.count)
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
navigationItem.title = "Home"
}
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleBeaconsUpdate", name: "beaconUpdate", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func handleBeaconsUpdate() {
let nearestBeacon:CLBeacon = app.lastBeacons![0] as CLBeacon
if(nearestBeacon.major == app.lastMajor || nearestBeacon.proximity == CLProximity.Unknown) {
return;
}
if (self.app.conferenceJsonGot == true) {
self.app.lastMajor = nearestBeacon.major
}
self.updateData()
self.conferenceSubView.hidden = false
self.noConferenceSubView.hidden = true
}
func updateData() {
let myConference: Conference = Conference.sharedInstance
if (self.app.conferenceJsonGot == true) {
titleLabel.text = myConference.title
addressLabel.text = myConference.address
startDayLabel.text = myConference.start_day
endDayLabel.text = myConference.end_day
if self.app.upCommingTalks == false {
self.calendarSubView.hidden = false
myColor = getRandomColor();
self.newFindClosestDates();
self.tableView.reloadData();
self.app.upCommingTalks = true
}
}
}
private func getConferencesFromAPI() {
let url = URLFactory.conferenceWithMajorAPI(10)
JSONService
.GET(url)
.success{json in {self.makeConference(json)} ~> {
self.app.conferenceJsonGot = true
}}
.failure(onFailure, queue: NSOperationQueue.mainQueue())
}
private func makeConference(json: AnyObject) {
let jsonParsed: JSON = JSON(json)
ConferenceModelBuilder.buildConferenceFromJSON(jsonParsed)
}
private func getBeaconsFromAPI() {
let url = URLFactory.beaconsAPI()
JSONService
.GET(url)
.success{json in {self.makeBeacons(json)} ~> { self.app.beaconJsonGot = true;}}
.failure(onFailure, queue: NSOperationQueue.mainQueue())
}
private func makeBeacons(json: AnyObject) {
let jsonParsed: JSON = JSON(json)
BeaconsModelBuilder.buildBeaconsFromJSON(jsonParsed)
}
private func getTopologyFromAPI() {
let url = URLFactory.buildingWithMajorAPI(10)
JSONService
.GET(url)
.success{json in {self.makeTopology(json)} ~> { self.app.topologyJsonGot = true;}}
.failure(onFailure, queue: NSOperationQueue.mainQueue())
}
private func makeTopology(json: AnyObject) {
let jsonParsed: JSON = JSON(json)
TopologyModelBuilder.buildTopologyFromJSON(jsonParsed)
}
private func onFailure(statusCode: Int, error: NSError?)
{
println("HTTP status code \(statusCode)")
let
title = "Error",
msg = error?.localizedDescription ?? "An error occurred.",
alert = UIAlertController(
title: title,
message: msg,
preferredStyle: .Alert)
alert.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(alert, animated: true, completion: nil)
}
//TableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: CustomCellHomeView = self.tableView.dequeueReusableCellWithIdentifier("cellHomeView") as CustomCellHomeView
//cell.textLabel?.text = self.items[indexPath.row]
//cell.setCell( calendar.title, room: "Room n°" , start_ts: "", end_ts: "", color: UIColor.greenColor())
if (after.count != 0){
let talks = self.after[indexPath.row]
cell.setCell(talks.title, start_ts: getTime(talks.start_ts), end_ts: getTime(talks.end_ts), abstract: talks.abstract, barColor: myColor)
}
//cell.setCellBis(self.items[indexPath.row])
//cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
return cell
}
func getTime(var date: Int)-> String{
var respondedDate = Double(date);
var date = NSDate(timeIntervalSince1970: respondedDate);
let formater: NSDateFormatter = NSDateFormatter()
formater.dateFormat = "H:mm"
let startTime = formater.stringFromDate(date)
return startTime;
}
func newFindClosestDates(){
let myConference: Conference = Conference.sharedInstance
var indexCount: Int = 0;
var indexTracks: Int = 0;
var indexSessions: Int = 0;
var indexTalks: Int = 0;
var indexFloors: Int = 0;
var indexRooms: Int = 0;
var indexCountSection: Int = 0;
var indexCountTalk: Int = 0;
var indexCountRoom: Int = 0;
var indexCountTrack: Int = 0;
// Load the element in the tableview
if(myConference.tracks?.count != nil){
// Loop for tracks
indexTracks = 0
while(indexTracks != myConference.tracks?.count){
// Loop for sessions
indexSessions = 0
while(indexSessions != myConference.tracks![indexTracks].sessions.count){
// Loop for talks
indexTalks = 0
while(indexTalks != myConference.tracks![indexTracks].sessions[indexSessions].talks.count){
// Insert talks
self.talk.insert(Talk(id: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].id, title: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].title, start_ts: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].start_ts, end_ts: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].end_ts, speaker:myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].speaker, abstract: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].abstract, body: myConference.tracks![indexTracks].sessions[indexSessions].talks[indexTalks].body), atIndex: indexCount);
indexCount += 1;
indexTalks += 1;
}
indexSessions += 1;
}
indexTracks += 1;
}
}
talk = talk.sorted({ $0.start_ts < $1.start_ts})
//Test Date
// let responseInitialDate = Double(1421832450)
// var date = NSDate(timeIntervalSince1970: responseInitialDate)
var indexDate = 0;
for(var indexTalks = 0; indexTalks < talk.count; indexTalks++) {
var tar = talk[indexTalks];
let date = NSDate()
var respondedDate = Double(tar.start_ts);
var dateTest = NSDate(timeIntervalSince1970: respondedDate);
if (dateTest.laterDate(date) != date){
self.after.insert(talk[indexTalks], atIndex: indexDate);
indexDate += 1;
}
}
after = after.sorted({ $0.start_ts < $1.start_ts})
}
func getRandomColor() -> UIColor {
var randomRed:CGFloat = CGFloat(drand48())
var randomGreen:CGFloat = CGFloat(drand48())
var randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
}
|
apache-2.0
|
19e4eaa786a5505b734707c9cec5015a
| 33.913495 | 707 | 0.605649 | 4.807051 | false | false | false | false |
KrishMunot/swift
|
test/DebugInfo/if-branchlocations.swift
|
6
|
1061
|
// RUN: %target-swift-frontend %s -emit-sil -emit-verbose-sil -g -o - | FileCheck %s
class NSURL {}
class NSPathControlItem {
var URL: NSURL?
}
class NSPathControl {
var clickedPathItem: NSPathControlItem?;
}
class AppDelegate {
func LogStr(_ message: String) {
}
func componentClicked(_ sender: AnyObject)
{
if let control = sender as? NSPathControl
{
LogStr( "Got a path control" )
if let item = control.clickedPathItem
{
LogStr( "Got an NSPathControlItem" )
// Verify that the branch's location is >= the cleanup's location.
// (The implicit false block of the conditional
// below inherits the location from the condition.)
// CHECK: br{{.*}}line:[[@LINE+1]]
if let url = item.URL
{
LogStr( "There is a url" )
}
// Verify that the branch's location is >= the cleanup's location.
// CHECK: strong_release{{.*}}$NSPathControlItem{{.*}}line:[[@LINE+2]]
// CHECK-NEXT: br{{.*}}line:[[@LINE+1]]
}
}
}
}
|
apache-2.0
|
33ba2b8e5c440aa18bbd2d9d19647650
| 25.525 | 84 | 0.590009 | 3.900735 | false | false | false | false |
cikelengfeng/Jude
|
Jude/Antlr4/atn/PredicateTransition.swift
|
2
|
1521
|
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// TODO: this is old comment:
/// A tree of semantic predicates from the grammar AST if label==SEMPRED.
/// In the ATN, labels will always be exactly one predicate, but the DFA
/// may have to combine a bunch of them as it collects predicates from
/// multiple ATN configurations into a single DFA state.
public final class PredicateTransition: AbstractPredicateTransition {
public let ruleIndex: Int
public let predIndex: Int
public let isCtxDependent: Bool
// e.g., $i ref in pred
public init(_ target: ATNState, _ ruleIndex: Int, _ predIndex: Int, _ isCtxDependent: Bool) {
self.ruleIndex = ruleIndex
self.predIndex = predIndex
self.isCtxDependent = isCtxDependent
super.init(target)
}
override
public func getSerializationType() -> Int {
return PredicateTransition.PREDICATE
}
override
public func isEpsilon() -> Bool {
return true
}
override
public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
return false
}
public func getPredicate() -> SemanticContext.Predicate {
return SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent)
}
public func toString() -> String {
return "pred_\(ruleIndex):\(predIndex)"
}
}
|
mit
|
5c44cfce2eb87dfcc90caed726541e46
| 28.823529 | 97 | 0.677844 | 4.408696 | false | false | false | false |
biohazardlover/NintendoEverything
|
Pods/ImageViewer/ImageViewer/Source/Extensions/UIColor.swift
|
5
|
654
|
//
// UIColor.swift
// ImageViewer
//
// Created by Ross Butler on 17/02/2017.
// Copyright © 2017 MailOnline. All rights reserved.
//
import UIKit
extension UIColor {
open func shadeDarker() -> UIColor {
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
let variance: CGFloat = 0.4
let newR = CGFloat.maximum(r * variance, 0.0),
newG = CGFloat.maximum(g * variance, 0.0),
newB = CGFloat.maximum(b * variance, 0.0)
return UIColor(red: newR, green: newG, blue: newB, alpha: 1.0)
}
}
|
mit
|
7466a264422e79305a3f2963f8d11071
| 25.12 | 82 | 0.566616 | 3.248756 | false | false | false | false |
bjvanlinschoten/Pala
|
Pala/Pala/LGSimpleChat.swift
|
1
|
33602
|
//
// SimpleChatController.swift
// SimpleChat
//
// Created by Logan Wright on 10/16/14.
// Copyright (c) 2014 Logan Wright. All rights reserved.
//
/*
Mozilla Public License
Version 2.0
https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)
*/
import UIKit
// MARK: Message
class LGChatMessage : NSObject {
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.content, forKey: "contentKey")
aCoder.encodeObject(self.sentBy.rawValue, forKey: "sentByKey")
aCoder.encodeObject(self.timeStamp, forKey: "timeStampKey")
}
enum SentBy : String {
case User = "LGChatMessageSentByUser"
case Opponent = "LGChatMessageSentByOpponent"
}
// MARK: ObjC Compatibility
/*
ObjC can't interact w/ enums properly, so this is used for converting compatible values.
*/
class func SentByUserString() -> String {
return LGChatMessage.SentBy.User.rawValue
}
class func SentByOpponentString() -> String {
return LGChatMessage.SentBy.Opponent.rawValue
}
var sentByString: String {
get {
return sentBy.rawValue
}
set {
if let sentBy = SentBy(rawValue: newValue) {
self.sentBy = sentBy
} else {
println("LGChatMessage.FatalError : Property Set : Incompatible string set to SentByString!")
}
}
}
// MARK: Public Properties
var sentBy: SentBy
var content: String
var timeStamp: NSTimeInterval?
required init(coder aDecoder: NSCoder) {
self.sentBy = SentBy(rawValue: aDecoder.decodeObjectForKey("sentByKey") as! String)!
self.content = aDecoder.decodeObjectForKey("contentKey") as! String
self.timeStamp = aDecoder.decodeObjectForKey("timeStampKey") as? NSTimeInterval
}
required init (content: String, sentBy: SentBy, timeStamp: NSTimeInterval? = nil){
self.sentBy = sentBy
self.timeStamp = timeStamp
self.content = content
}
// MARK: ObjC Compatibility
convenience init (content: String, sentByString: String) {
if let sentBy = SentBy(rawValue: sentByString) {
self.init(content: content, sentBy: sentBy, timeStamp: nil)
} else {
fatalError("LGChatMessage.FatalError : Initialization : Incompatible string set to SentByString!")
}
}
convenience init (content: String, sentByString: String, timeStamp: NSTimeInterval) {
if let sentBy = SentBy(rawValue: sentByString) {
self.init(content: content, sentBy: sentBy, timeStamp: timeStamp)
} else {
fatalError("LGChatMessage.FatalError : Initialization : Incompatible string set to SentByString!")
}
}
}
// MARK: Message Cell
class LGChatMessageCell : UITableViewCell {
// MARK: Global MessageCell Appearance Modifier
struct Appearance {
static var opponentColor = UIColor(hexString: "009999")
static var userColor = UIColor(hexString: "FF7400")
static var font: UIFont = UIFont.systemFontOfSize(17.0)
}
/*
These methods are included for ObjC compatibility. If using Swift, you can set the Appearance variables directly.
*/
class func setAppearanceOpponentColor(opponentColor: UIColor) {
Appearance.opponentColor = opponentColor
}
class func setAppearanceUserColor(userColor: UIColor) {
Appearance.userColor = userColor
}
class func setAppearanceFont(font: UIFont) {
Appearance.font = font
}
// MARK: Message Bubble TextView
private lazy var textView: MessageBubbleTextView = {
let textView = MessageBubbleTextView(frame: CGRectZero, textContainer: nil)
self.contentView.addSubview(textView)
return textView
}()
private class MessageBubbleTextView : UITextView {
override init(frame: CGRect = CGRectZero, textContainer: NSTextContainer? = nil) {
super.init(frame: frame, textContainer: textContainer)
self.font = Appearance.font
self.scrollEnabled = false
self.editable = false
self.textContainerInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
self.layer.cornerRadius = 5
self.layer.borderWidth = 2.0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: ImageView
private lazy var opponentImageView: UIImageView = {
let opponentImageView = UIImageView()
opponentImageView.hidden = true
opponentImageView.bounds.size = CGSize(width: self.minimumHeight, height: self.minimumHeight)
let halfWidth = CGRectGetWidth(opponentImageView.bounds) / 2.0
let halfHeight = CGRectGetHeight(opponentImageView.bounds) / 2.0
// Center the imageview vertically to the textView when it is singleLine
let textViewSingleLineCenter = self.textView.textContainerInset.top + (Appearance.font.lineHeight / 2.0)
opponentImageView.center = CGPointMake(self.padding + halfWidth, textViewSingleLineCenter)
opponentImageView.backgroundColor = UIColor.lightTextColor()
opponentImageView.layer.rasterizationScale = UIScreen.mainScreen().scale
opponentImageView.layer.shouldRasterize = true
opponentImageView.layer.cornerRadius = halfHeight
opponentImageView.layer.masksToBounds = true
self.contentView.addSubview(opponentImageView)
return opponentImageView
}()
// MARK: Sizing
private let padding: CGFloat = 5.0
private let minimumHeight: CGFloat = 30.0 // arbitrary minimum height
private var size = CGSizeZero
private var maxSize: CGSize {
get {
let maxWidth = CGRectGetWidth(self.bounds) * 0.75 // Cells can take up to 3/4 of screen
let maxHeight = CGFloat.max
return CGSize(width: maxWidth, height: maxHeight)
}
}
// MARK: Setup Call
/*!
Use this in cellForRowAtIndexPath to setup the cell.
*/
func setupWithMessage(message: LGChatMessage) -> CGSize {
textView.text = message.content
size = textView.sizeThatFits(maxSize)
if size.height < minimumHeight {
size.height = minimumHeight
}
textView.bounds.size = size
self.styleTextViewForSentBy(message.sentBy)
return size
}
// MARK: TextBubble Styling
private func styleTextViewForSentBy(sentBy: LGChatMessage.SentBy) {
let halfTextViewWidth = CGRectGetWidth(self.textView.bounds) / 2.0
let targetX = halfTextViewWidth + padding
let halfTextViewHeight = CGRectGetHeight(self.textView.bounds) / 2.0
switch sentBy {
case .Opponent:
self.textView.center.x = targetX
self.textView.center.y = halfTextViewHeight
self.textView.layer.borderColor = Appearance.opponentColor!.CGColor
if self.opponentImageView.image != nil {
self.opponentImageView.hidden = false
self.textView.center.x += CGRectGetWidth(self.opponentImageView.bounds) + padding
}
case .User:
self.opponentImageView.hidden = true
self.textView.center.x = CGRectGetWidth(self.bounds) - targetX
self.textView.center.y = halfTextViewHeight
self.textView.layer.borderColor = Appearance.userColor!.CGColor
}
}
}
// MARK: Chat Controller
@objc protocol LGChatControllerDelegate {
optional func shouldChatController(chatController: LGChatController, addMessage message: LGChatMessage) -> Bool
optional func chatController(chatController: LGChatController, didAddNewMessage message: LGChatMessage)
}
class LGChatController : UIViewController, UITableViewDelegate, UITableViewDataSource, LGChatInputDelegate {
// MARK: Constants
private struct Constants {
static let MessagesSection: Int = 0;
static let MessageCellIdentifier: String = "LGChatController.Constants.MessageCellIdentifier"
}
// MARK: Public Properties
/*!
Use this to set the messages to be displayed
*/
var messages: [LGChatMessage] = []
var opponentImage: UIImage?
weak var delegate: LGChatControllerDelegate?
// MARK: Private Properties
private let sizingCell = LGChatMessageCell()
private let tableView: UITableView = UITableView()
private let chatInput = LGChatInput(frame: CGRectZero)
private var bottomChatInputConstraint: NSLayoutConstraint!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.listenForKeyboardChanges()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.scrollToBottom()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.unregisterKeyboardObservers()
}
deinit {
/*
Need to remove delegate and datasource or they will try to send scrollView messages.
*/
self.tableView.delegate = nil
self.tableView.dataSource = nil
}
// MARK: Setup
private func setup() {
self.setupTableView()
self.setupChatInput()
self.setupLayoutConstraints()
}
private func setupTableView() {
tableView.allowsSelection = false
tableView.separatorStyle = .None
tableView.frame = self.view.bounds
tableView.registerClass(LGChatMessageCell.classForCoder(), forCellReuseIdentifier: "identifier")
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
self.view.addSubview(tableView)
}
private func setupChatInput() {
chatInput.delegate = self
self.view.addSubview(chatInput)
}
private func setupLayoutConstraints() {
chatInput.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addConstraints(self.chatInputConstraints())
self.view.addConstraints(self.tableViewConstraints())
}
private func chatInputConstraints() -> [NSLayoutConstraint] {
self.bottomChatInputConstraint = NSLayoutConstraint(item: chatInput, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
let leftConstraint = NSLayoutConstraint(item: chatInput, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: chatInput, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
return [leftConstraint, self.bottomChatInputConstraint, rightConstraint]
}
private func tableViewConstraints() -> [NSLayoutConstraint] {
let leftConstraint = NSLayoutConstraint(item: tableView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: tableView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: chatInput, attribute: .Top, multiplier: 1.0, constant: 0)
return [rightConstraint, leftConstraint, topConstraint, bottomConstraint]//, rightConstraint, bottomConstraint]
}
// MARK: Keyboard Notifications
private func listenForKeyboardChanges() {
let defaultCenter = NSNotificationCenter.defaultCenter()
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
defaultCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
defaultCenter.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
} else {
defaultCenter.addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
}
private func unregisterKeyboardObservers() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: iOS 8 Keyboard Animations
func keyboardWillChangeFrame(note: NSNotification) {
/*
NOTE: For iOS 8 Only, will cause autolayout issues in iOS 7
*/
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
var keyboardFrame = (keyboardAnimationDetail[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
if let window = self.view.window {
keyboardFrame = window.convertRect(keyboardFrame, toView: self.view)
}
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
var chatInputOffset = -(CGRectGetHeight(self.view.bounds) - CGRectGetMinY(keyboardFrame))
if chatInputOffset > 0 {
chatInputOffset = 0
}
self.bottomChatInputConstraint.constant = chatInputOffset
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
// MARK: iOS 7 Compatibility Keyboard Animations
func keyboardWillShow(note: NSNotification) {
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let keyboardFrame = (keyboardAnimationDetail[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let keyboardHeight = UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) ? CGRectGetHeight(keyboardFrame) : CGRectGetWidth(keyboardFrame)
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
self.bottomChatInputConstraint.constant = -keyboardHeight
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
func keyboardWillHide(note: NSNotification) {
let keyboardAnimationDetail = note.userInfo!
let duration = keyboardAnimationDetail[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
let animationCurve = keyboardAnimationDetail[UIKeyboardAnimationCurveUserInfoKey] as! UInt
self.tableView.scrollEnabled = false
self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
self.view.layoutIfNeeded()
self.bottomChatInputConstraint.constant = 0.0
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(animationCurve), animations: { () -> Void in
self.view.layoutIfNeeded()
self.scrollToBottom()
}, completion: {(finished) -> () in
self.tableView.scrollEnabled = true
self.tableView.decelerationRate = UIScrollViewDecelerationRateNormal
})
}
// MARK: Rotation
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration)
self.tableView.reloadData()
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
super.didRotateFromInterfaceOrientation(fromInterfaceOrientation)
UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.scrollToBottom()
}, completion: nil)
}
// MARK: Scrolling
private func scrollToBottom() {
if messages.count > 0 {
var lastItemIdx = self.tableView.numberOfRowsInSection(Constants.MessagesSection) - 1
if lastItemIdx < 0 {
lastItemIdx = 0
}
let lastIndexPath = NSIndexPath(forRow: lastItemIdx, inSection: Constants.MessagesSection)
self.tableView.scrollToRowAtIndexPath(lastIndexPath, atScrollPosition: .Bottom, animated: false)
}
}
// MARK: New messages
func addNewMessage(message: LGChatMessage) {
messages += [message]
tableView.reloadData()
self.scrollToBottom()
self.delegate?.chatController?(self, didAddNewMessage: message)
}
// MARK: SwiftChatInputDelegate
func chatInputDidResize(chatInput: LGChatInput) {
self.scrollToBottom()
}
func chatInput(chatInput: LGChatInput, didSendMessage message: String) {
let newMessage = LGChatMessage(content: message, sentBy: .User)
var shouldSendMessage = true
if let value = self.delegate?.shouldChatController?(self, addMessage: newMessage) {
shouldSendMessage = value
}
if shouldSendMessage {
self.addNewMessage(newMessage)
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let padding: CGFloat = 10.0
sizingCell.bounds.size.width = CGRectGetWidth(self.view.bounds)
let height = self.sizingCell.setupWithMessage(messages[indexPath.row]).height + padding;
return height
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.dragging {
self.chatInput.textView.resignFirstResponder()
}
}
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messages.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! LGChatMessageCell
let message = self.messages[indexPath.row]
cell.opponentImageView.image = message.sentBy == .Opponent ? self.opponentImage : nil
cell.setupWithMessage(message)
return cell;
}
}
// MARK: Chat Input
protocol LGChatInputDelegate : class {
func chatInputDidResize(chatInput: LGChatInput)
func chatInput(chatInput: LGChatInput, didSendMessage message: String)
}
class LGChatInput : UIView, LGStretchyTextViewDelegate {
// MARK: Styling
struct Appearance {
static var includeBlur = true
static var tintColor = UIColor(red: 0.0, green: 120 / 255.0, blue: 255 / 255.0, alpha: 1.0)
static var backgroundColor = UIColor.whiteColor()
static var textViewFont = UIFont.systemFontOfSize(17.0)
static var textViewTextColor = UIColor.darkTextColor()
static var textViewBackgroundColor = UIColor.whiteColor()
}
/*
These methods are included for ObjC compatibility. If using Swift, you can set the Appearance variables directly.
*/
class func setAppearanceIncludeBlur(includeBlur: Bool) {
Appearance.includeBlur = includeBlur
}
class func setAppearanceTintColor(color: UIColor) {
Appearance.tintColor = color
}
class func setAppearanceBackgroundColor(color: UIColor) {
Appearance.backgroundColor = color
}
class func setAppearanceTextViewFont(textViewFont: UIFont) {
Appearance.textViewFont = textViewFont
}
class func setAppearanceTextViewTextColor(textColor: UIColor) {
Appearance.textViewTextColor = textColor
}
class func setAppearanceTextViewBackgroundColor(color: UIColor) {
Appearance.textViewBackgroundColor = color
}
// MARK: Public Properties
var textViewInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
weak var delegate: LGChatInputDelegate?
// MARK: Private Properties
private let textView = LGStretchyTextView(frame: CGRectZero, textContainer: nil)
private let sendButton = UIButton.buttonWithType(.System) as! UIButton
private let blurredBackgroundView: UIToolbar = UIToolbar()
private var heightConstraint: NSLayoutConstraint!
private var sendButtonHeightConstraint: NSLayoutConstraint!
// MARK: Initialization
override init(frame: CGRect = CGRectZero) {
super.init(frame: frame)
self.setup()
self.stylize()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup
func setup() {
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.setupSendButton()
self.setupSendButtonConstraints()
self.setupTextView()
self.setupTextViewConstraints()
self.setupBlurredBackgroundView()
self.setupBlurredBackgroundViewConstraints()
}
func setupTextView() {
textView.bounds = UIEdgeInsetsInsetRect(self.bounds, self.textViewInsets)
textView.stretchyTextViewDelegate = self
textView.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
self.styleTextView()
self.addSubview(textView)
}
func styleTextView() {
textView.layer.rasterizationScale = UIScreen.mainScreen().scale
textView.layer.shouldRasterize = true
textView.layer.cornerRadius = 5.0
textView.layer.borderWidth = 1.0
textView.layer.borderColor = UIColor(white: 0.0, alpha: 0.2).CGColor
}
func setupSendButton() {
self.sendButton.enabled = false
self.sendButton.setTitle("Send", forState: .Normal)
self.sendButton.addTarget(self, action: "sendButtonPressed:", forControlEvents: .TouchUpInside)
self.sendButton.bounds = CGRect(x: 0, y: 0, width: 40, height: 1)
self.addSubview(sendButton)
}
func setupSendButtonConstraints() {
self.sendButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.sendButton.removeConstraints(self.sendButton.constraints())
// TODO: Fix so that button height doesn't change on first newLine
let rightConstraint = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.sendButton, attribute: .Right, multiplier: 1.0, constant: textViewInsets.right)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.sendButton, attribute: .Bottom, multiplier: 1.0, constant: textViewInsets.bottom)
let widthConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 40)
sendButtonHeightConstraint = NSLayoutConstraint(item: self.sendButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 30)
self.addConstraints([sendButtonHeightConstraint, widthConstraint, rightConstraint, bottomConstraint])
}
func setupTextViewConstraints() {
self.textView.setTranslatesAutoresizingMaskIntoConstraints(false)
let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: self.textView, attribute: .Top, multiplier: 1.0, constant: -textViewInsets.top)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: self.textView, attribute: .Left, multiplier: 1, constant: -textViewInsets.left)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.textView, attribute: .Bottom, multiplier: 1, constant: textViewInsets.bottom)
let rightConstraint = NSLayoutConstraint(item: self.textView, attribute: .Right, relatedBy: .Equal, toItem: self.sendButton, attribute: .Left, multiplier: 1, constant: -textViewInsets.right)
heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.00, constant: 40)
self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint, heightConstraint])
}
func setupBlurredBackgroundView() {
self.addSubview(self.blurredBackgroundView)
self.sendSubviewToBack(self.blurredBackgroundView)
}
func setupBlurredBackgroundViewConstraints() {
self.blurredBackgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Top, multiplier: 1.0, constant: 0)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Left, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Bottom, multiplier: 1.0, constant: 0)
let rightConstraint = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.blurredBackgroundView, attribute: .Right, multiplier: 1.0, constant: 0)
self.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint])
}
// MARK: Styling
func stylize() {
self.textView.backgroundColor = Appearance.textViewBackgroundColor
self.sendButton.tintColor = Appearance.tintColor
self.textView.tintColor = Appearance.tintColor
self.textView.font = Appearance.textViewFont
self.textView.textColor = Appearance.textViewTextColor
self.blurredBackgroundView.hidden = !Appearance.includeBlur
self.backgroundColor = Appearance.backgroundColor
}
// MARK: StretchyTextViewDelegate
func stretchyTextViewDidChangeSize(textView: LGStretchyTextView) {
let textViewHeight = CGRectGetHeight(textView.bounds)
if count(textView.text) == 0 {
self.sendButtonHeightConstraint.constant = textViewHeight
}
let targetConstant = textViewHeight + textViewInsets.top + textViewInsets.bottom
self.heightConstraint.constant = targetConstant
self.delegate?.chatInputDidResize(self)
}
func stretchyTextView(textView: LGStretchyTextView, validityDidChange isValid: Bool) {
self.sendButton.enabled = isValid
}
// MARK: Button Presses
func sendButtonPressed(sender: UIButton) {
if count(self.textView.text) > 0 {
self.delegate?.chatInput(self, didSendMessage: self.textView.text)
self.textView.text = ""
}
}
}
// MARK: Text View
@objc protocol LGStretchyTextViewDelegate {
func stretchyTextViewDidChangeSize(chatInput: LGStretchyTextView)
optional func stretchyTextView(textView: LGStretchyTextView, validityDidChange isValid: Bool)
}
class LGStretchyTextView : UITextView, UITextViewDelegate {
// MARK: Delegate
weak var stretchyTextViewDelegate: LGStretchyTextViewDelegate?
// MARK: Public Properties
var maxHeightPortrait: CGFloat = 160
var maxHeightLandScape: CGFloat = 60
var maxHeight: CGFloat {
get {
return UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) ? maxHeightPortrait : maxHeightLandScape
}
}
// MARK: Private Properties
private var maxSize: CGSize {
get {
return CGSize(width: CGRectGetWidth(self.bounds), height: self.maxHeightPortrait)
}
}
private var _isValid = false
private var isValid: Bool {
get {
return _isValid
}
set {
if _isValid != newValue {
_isValid = newValue
self.stretchyTextViewDelegate?.stretchyTextView?(self, validityDidChange: _isValid)
}
}
}
private let sizingTextView = UITextView()
// MARK: Property Overrides
override var contentSize: CGSize {
didSet {
self.resizeAndAlign()
}
}
override var font: UIFont! {
didSet {
sizingTextView.font = font
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
sizingTextView.textContainerInset = textContainerInset
}
}
// MARK: Initializers
override init(frame: CGRect = CGRectZero, textContainer: NSTextContainer? = nil) {
super.init(frame: frame, textContainer: textContainer);
self.setup()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup
func setup() {
self.font = UIFont.systemFontOfSize(17.0)
self.textContainerInset = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
self.delegate = self
}
// MARK: Resize & Align
func resizeAndAlign() {
self.resize()
self.align()
}
// MARK: Sizing
func resize() {
self.bounds.size.height = self.targetHeight()
self.stretchyTextViewDelegate?.stretchyTextViewDidChangeSize(self)
}
func targetHeight() -> CGFloat {
/*
There is an issue when calling `sizeThatFits` on self that results in really weird drawing issues with aligning line breaks ("\n"). For that reason, we have a textView whose job it is to size the textView. It's excess, but apparently necessary. If there's been an update to the system and this is no longer necessary, or if you find a better solution. Please remove it and submit a pull request as I'd rather not have it.
*/
sizingTextView.text = self.text
let targetSize = sizingTextView.sizeThatFits(maxSize)
var targetHeight = targetSize.height
let maxHeight = self.maxHeight
return targetHeight < maxHeight ? targetHeight : maxHeight
}
// MARK: Alignment
func align() {
let caretRect: CGRect = self.caretRectForPosition(self.selectedTextRange?.end)
let topOfLine = CGRectGetMinY(caretRect)
let bottomOfLine = CGRectGetMaxY(caretRect)
let contentOffsetTop = self.contentOffset.y
let bottomOfVisibleTextArea = contentOffsetTop + CGRectGetHeight(self.bounds)
/*
If the caretHeight and the inset padding is greater than the total bounds then we are on the first line and aligning will cause bouncing.
*/
let caretHeightPlusInsets = CGRectGetHeight(caretRect) + self.textContainerInset.top + self.textContainerInset.bottom
if caretHeightPlusInsets < CGRectGetHeight(self.bounds) {
var overflow: CGFloat = 0.0
if topOfLine < contentOffsetTop + self.textContainerInset.top {
overflow = topOfLine - contentOffsetTop - self.textContainerInset.top
} else if bottomOfLine > bottomOfVisibleTextArea - self.textContainerInset.bottom {
overflow = (bottomOfLine - bottomOfVisibleTextArea) + self.textContainerInset.bottom
}
self.contentOffset.y += overflow
}
}
// MARK: UITextViewDelegate
func textViewDidChangeSelection(textView: UITextView) {
self.align()
}
func textViewDidChange(textView: UITextView) {
// TODO: Possibly filter spaces and newlines
self.isValid = count(textView.text) > 0
}
}
|
mit
|
bda086f62bb6a0e662bca36aa4e40aba
| 38.625 | 431 | 0.674662 | 5.180697 | false | false | false | false |
dsoisson/SwiftLearningExercises
|
Exercise5.playground/Pages/Ex_2_Refactor.xcplaygroundpage/Sources/returnFirstNames.swift
|
1
|
1469
|
import Foundation
//var allNames: String = ""
//var counter: Int
//
//public func firstNames(arrayName: Array<String>) -> (String) {
// for index in arrayName {
// counter = counter + 1
// Print(counter)
// print(index)
// arrayName[index]
// }
//
//}
public func intro(students: [[String]]) -> String {
var myName = ""
myName = "My name is \(students[0][0]), my email is \(students[0][2])"
return myName
}
public func otherStudents(students: [[String]]) -> String {
var names = ""
for student in students {
names += student[0]+", "
}
return "the other students are \(names)"
}
public func dropStudent(var students: [[String]], student: String) -> (String, [[String]]) {
var studentFound = false
var index = 0
var notice = ""
for name in students[students.indices]{
index++
if name.first! == student {
studentFound = !studentFound
}
}
if studentFound {
notice = ("\(student) was found in this class and will be dropped.")
students = [students.removeAtIndex(index-1)]
} else {
notice = ("\(student) is not in this class and cannot be dropped.")
}
return (notice, students)
}
//public func addStudent(var students: [[String]], student: [String]) -> [[String]] {
// var newArray = [[String]]
// students.append(student)
//
//// newArray = students.append(student)
//}
|
mit
|
b49056c29f8c932b13c9c32b2f0ad9f4
| 24.327586 | 92 | 0.575902 | 3.855643 | false | false | false | false |
BenedictC/BCOObjectStore
|
BCOObjectStoreTests/BCOIndexTests.swift
|
1
|
2398
|
//
// BCOIndexTests.swift
// BCOObjectStore
//
// Created by Benedict Cohen on 06/02/2015.
// Copyright (c) 2015 Benedict Cohen. All rights reserved.
//
import Cocoa
import XCTest
class BCOIndexTests: XCTestCase {
var original: BCOIndex?
var objects: [AnyObject]?
var indexValues: [AnyObject]?
var references: [BCOObjectReference]?
override func setUp() {
let description = BCOIndexDescription(indexValueGenerator:{
return NSNumber(integer:$0.length())
},
valueComparator:{
return $0.compare($1)
})
let original = BCOIndex(indexDescription: description)
var objects:[AnyObject] = []
var indexValues:[AnyObject] = []
var references:[BCOObjectReference] = []
for (var i = 0; i < 100; i++) {
let obj:String = {
var o = ""
for (var j = 0; j < i; j++) {o += "-"}
return o
}()
let reference = BCOObjectReference(forObject:obj)
let value:AnyObject = original.generateIndexValueForObject(obj)
objects.append(obj)
references.append(reference)
indexValues.append(value)
original.addReference(reference, forIndexValue: value)
}
self.objects = objects
self.indexValues = indexValues
self.references = references
self.original = original
}
//MARK: Copying
func testOriginalDoesNotModifyCopy() {
//Given
let original = self.original!
let copy = original.copy() as BCOIndex
//When
original.removeReference(self.references![0], forIndexValue:self.indexValues![0])
//Then
let expected = NSSet(objects:self.references![0])
let actual = copy.referencesForValue(self.indexValues![0])
XCTAssertEqual(expected, actual)
}
func testCopyDoesNotModifyOriginal() {
//Given
let original = self.original!
let copy = original.copy() as BCOIndex
//When
copy.removeReference(self.references![0], forIndexValue:self.indexValues![0])
//Then
let expected = NSSet(objects:self.references![0])
let actual = original.referencesForValue(self.indexValues![0])
XCTAssertEqual(expected, actual)
}
//MARK: Object Access
//TODO:
}
|
mit
|
826d5a93d06e3b029bef3467f6537434
| 23.979167 | 89 | 0.595079 | 4.367942 | false | true | false | false |
mittenimraum/CVGenericDataSource
|
Sources/CVGenericDataSourceSection.swift
|
1
|
3980
|
//
// CVGenericDataSourceSection.swift
// CVGenericDataSource
//
// Created by Stephan Schulz on 12.04.17.
// Copyright © 2017 Stephan Schulz. All rights reserved.
//
import Foundation
// MARK: - CVSectionProtocol
public protocol CVSectionProtocol {
associatedtype Item: Equatable
var items: [Item] { get set }
var headerTitle: String? { get }
var footerTitle: String? { get }
}
// MARK: - CVSectionOptionProtocol
public protocol CVSectionOptionProtocol {
associatedtype Item: Equatable
var insets: UIEdgeInsets? { get }
var headerShouldAppear: Bool { get }
var footerShouldAppear: Bool { get }
var lineSpacing: CGFloat? { get }
var cellSpacing: CGFloat? { get }
func selection(_ item: Item?, _ index: Int) -> Void
}
// MARK: - CVSection
public struct CVSection<Item: Equatable>: CVSectionProtocol {
// MARK: - Options
public enum CVSectionOption {
case insets(UIEdgeInsets)
case selection(CVSectionSelection)
case headerShouldAppear(Bool)
case footerShouldAppear(Bool)
case lineSpacing(CGFloat)
case cellSpacing(CGFloat)
}
public var options: [CVSectionOption]? {
didSet {
guard let options = options else {
return
}
for option in options {
switch option {
case let .insets(value):
_optionInsets = value
case let .selection(value):
_optionSelection = value
case let .headerShouldAppear(value):
_optionHeaderShouldAppear = value
case let .footerShouldAppear(value):
_optionFooterShouldAppear = value
case let .lineSpacing(value):
_optionLineSpacing = value
case let .cellSpacing(value):
_optionCellSpacing = value
}
}
}
}
fileprivate var _optionLineSpacing: CGFloat?
fileprivate var _optionCellSpacing: CGFloat?
fileprivate var _optionFooterShouldAppear: Bool?
fileprivate var _optionHeaderShouldAppear: Bool?
fileprivate var _optionInsets: UIEdgeInsets?
fileprivate var _optionSelection: CVSectionSelection?
// MARK: - Constants
public let headerTitle: String?
public let footerTitle: String?
// MARK: - Variables
public var items: [Item]
public var count: Int {
return items.count
}
// MARK: - Init
public init(items: Item..., headerTitle: String? = nil, footerTitle: String? = nil, _ options: [CVSectionOption]? = nil) {
self.init(items, headerTitle: headerTitle, footerTitle: footerTitle, options)
}
public init(_ items: [Item], headerTitle: String? = nil, footerTitle: String? = nil, _ options: [CVSectionOption]? = nil) {
self.items = items
self.headerTitle = headerTitle
self.footerTitle = footerTitle
defer {
self.options = options
}
}
// MARK: - Subscript
public subscript(index: Int) -> Item {
get {
return items[index]
}
set {
items[index] = newValue
}
}
}
// MARK: - Extensions
extension CVSection: CVSectionOptionProtocol {
public typealias CVSectionSelection = (_ item: Item?, _ index: Int) -> Void
public var cellSpacing: CGFloat? {
return _optionCellSpacing
}
public var lineSpacing: CGFloat? {
return _optionLineSpacing
}
public var insets: UIEdgeInsets? {
return _optionInsets
}
public var headerShouldAppear: Bool {
return _optionHeaderShouldAppear ?? true
}
public var footerShouldAppear: Bool {
return _optionFooterShouldAppear ?? false
}
public func selection(_ item: Item?, _ index: Int) {
_optionSelection?(item, index)
}
}
|
mit
|
24a3df5dd5d225abd77122f894e5ae3a
| 25.177632 | 127 | 0.601156 | 4.74821 | false | false | false | false |
bparish628/iFarm-Health
|
iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift
|
4
|
14217
|
//
// RadarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class RadarChartRenderer: LineRadarRenderer
{
@objc open weak var chart: RadarChartView?
@objc public init(chart: RadarChartView?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
open override func drawData(context: CGContext)
{
guard let chart = chart else { return }
let radarData = chart.data
if radarData != nil
{
let mostEntries = radarData?.maxEntryCountSet?.entryCount ?? 0
for set in radarData!.dataSets as! [IRadarChartDataSet]
{
if set.isVisible
{
drawDataSet(context: context, dataSet: set, mostEntries: mostEntries)
}
}
}
}
/// Draws the RadarDataSet
///
/// - parameter context:
/// - parameter dataSet:
/// - parameter mostEntries: the entry count of the dataset with the most entries
@objc internal func drawDataSet(context: CGContext, dataSet: IRadarChartDataSet, mostEntries: Int)
{
guard let
chart = chart,
let animator = animator
else { return }
context.saveGState()
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let entryCount = dataSet.entryCount
let path = CGMutablePath()
var hasMovedToPoint = false
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat((e.y - chart.chartYMin) * Double(factor) * phaseY),
angle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
if p.x.isNaN
{
continue
}
if !hasMovedToPoint
{
path.move(to: p)
hasMovedToPoint = true
}
else
{
path.addLine(to: p)
}
}
// if this is the largest set, close it
if dataSet.entryCount < mostEntries
{
// if this is not the largest set, draw a line to the center before closing
path.addLine(to: center)
}
path.closeSubpath()
// draw filled
if dataSet.isDrawFilledEnabled
{
if dataSet.fill != nil
{
drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
// draw the line (only if filled is disabled or alpha is below 255)
if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0
{
context.setStrokeColor(dataSet.color(atIndex: 0).cgColor)
context.setLineWidth(dataSet.lineWidth)
context.setAlpha(1.0)
context.beginPath()
context.addPath(path)
context.strokePath()
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let chart = chart,
let data = chart.data,
let animator = animator
else { return }
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let yoffset = CGFloat(5.0)
for i in 0 ..< data.dataSetCount
{
let dataSet = data.getDataSetByIndex(i) as! IRadarChartDataSet
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let entryCount = dataSet.entryCount
let iconsOffset = dataSet.iconsOffset
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(e.y - chart.chartYMin) * factor * CGFloat(phaseY),
angle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight),
align: .center,
attributes: [NSAttributedStringKey.font: valueFont,
NSAttributedStringKey.foregroundColor: dataSet.valueTextColorAt(j)]
)
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var pIcon = ChartUtils.getPosition(
center: center,
dist: CGFloat(e.y) * factor * CGFloat(phaseY) + iconsOffset.y,
angle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
pIcon.y += iconsOffset.x
ChartUtils.drawImage(context: context,
image: icon,
x: pIcon.x,
y: pIcon.y,
size: icon.size)
}
}
}
}
open override func drawExtras(context: CGContext)
{
drawWeb(context: context)
}
fileprivate var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawWeb(context: CGContext)
{
guard
let chart = chart,
let data = chart.data
else { return }
let sliceangle = chart.sliceAngle
context.saveGState()
// calculate the factor that is needed for transforming the value to
// pixels
let factor = chart.factor
let rotationangle = chart.rotationAngle
let center = chart.centerOffsets
// draw the web lines that come from the center
context.setLineWidth(chart.webLineWidth)
context.setStrokeColor(chart.webColor.cgColor)
context.setAlpha(chart.webAlpha)
let xIncrements = 1 + chart.skipWebLineCount
let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0
for i in stride(from: 0, to: maxEntryCount, by: xIncrements)
{
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(chart.yRange) * factor,
angle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
// draw the inner-web
context.setLineWidth(chart.innerWebLineWidth)
context.setStrokeColor(chart.innerWebColor.cgColor)
context.setAlpha(chart.webAlpha)
let labelCount = chart.yAxis.entryCount
for j in 0 ..< labelCount
{
for i in 0 ..< data.entryCount
{
let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor
let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle)
let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
}
context.restoreGState()
}
fileprivate var _highlightPointBuffer = CGPoint()
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let chart = chart,
let radarData = chart.data as? RadarChartData,
let animator = animator
else { return }
context.saveGState()
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value pixels
let factor = chart.factor
let center = chart.centerOffsets
for high in indices
{
guard
let set = chart.data?.getDataSetByIndex(high.dataSetIndex) as? IRadarChartDataSet,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForIndex(Int(high.x)) as? RadarChartDataEntry
else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setLineWidth(radarData.highlightLineWidth)
if radarData.highlightLineDashLengths != nil
{
context.setLineDash(phase: radarData.highlightLineDashPhase, lengths: radarData.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(set.highlightColor.cgColor)
let y = e.y - chart.chartYMin
_highlightPointBuffer = ChartUtils.getPosition(
center: center,
dist: CGFloat(y) * factor * CGFloat(animator.phaseY),
angle: sliceangle * CGFloat(high.x) * CGFloat(animator.phaseX) + chart.rotationAngle)
high.setDraw(pt: _highlightPointBuffer)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
if set.isDrawHighlightCircleEnabled
{
if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN
{
var strokeColor = set.highlightCircleStrokeColor
if strokeColor == nil
{
strokeColor = set.color(atIndex: 0)
}
if set.highlightCircleStrokeAlpha < 1.0
{
strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha)
}
drawHighlightCircle(
context: context,
atPoint: _highlightPointBuffer,
innerRadius: set.highlightCircleInnerRadius,
outerRadius: set.highlightCircleOuterRadius,
fillColor: set.highlightCircleFillColor,
strokeColor: strokeColor,
strokeWidth: set.highlightCircleStrokeWidth)
}
}
}
context.restoreGState()
}
@objc internal func drawHighlightCircle(
context: CGContext,
atPoint point: CGPoint,
innerRadius: CGFloat,
outerRadius: CGFloat,
fillColor: NSUIColor?,
strokeColor: NSUIColor?,
strokeWidth: CGFloat)
{
context.saveGState()
if let fillColor = fillColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
if innerRadius > 0.0
{
context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0))
}
context.setFillColor(fillColor.cgColor)
context.fillPath(using: .evenOdd)
}
if let strokeColor = strokeColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
context.setStrokeColor(strokeColor.cgColor)
context.setLineWidth(strokeWidth)
context.strokePath()
}
context.restoreGState()
}
}
|
apache-2.0
|
aa343b9f28ffb19ab079fb432e9a5123
| 33.011962 | 151 | 0.517479 | 5.75587 | false | false | false | false |
iSapozhnik/LoadingViewController
|
LoadingViewController/Classes/Views/LoadingViews/IndicatorLoadingView.swift
|
2
|
2017
|
//
// IndicatorLoadingView.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 23.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
enum IndicatorLoadingViewStyle {
case small
case big
case smallTitle
case bigTitle
}
class IndicatorLoadingView: LoadingView {
var activity = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
var titleLabel: UILabel?
var style = IndicatorLoadingViewStyle.big
init(style: IndicatorLoadingViewStyle) {
super.init(frame: CGRect.zero)
self.style = style
defaultInitializer()
}
override init(frame: CGRect) {
super.init(frame: frame)
defaultInitializer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInitializer()
}
fileprivate func defaultInitializer() {
switch style {
case .big: bigActivity()
case .small: smallActivity()
case .smallTitle: smallTitle()
case .bigTitle: bigTitle()
}
}
fileprivate func smallActivity() {
activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
addActivity()
}
fileprivate func bigActivity() {
activity = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
addActivity()
}
fileprivate func defaultTitleLabel() {
titleLabel = UILabel(frame: CGRect(x: 0,y: 0,width: 100,height: 44))
titleLabel?.textAlignment = .center
titleLabel?.textColor = UIColor.lightGray
addSubview(titleLabel!)
}
fileprivate func smallTitle() {
smallActivity()
addActivity()
defaultTitleLabel()
}
fileprivate func bigTitle() {
bigActivity()
addActivity()
defaultTitleLabel()
}
fileprivate func addActivity() {
activity.startAnimating()
activity.color = UIColor.darkGray
addSubview(activity)
}
override func layoutSubviews() {
super.layoutSubviews()
activity.center = CGPoint(x: bounds.midX, y: bounds.midY)
titleLabel?.center = CGPoint(x: bounds.midX, y: bounds.midY + 40)
}
override func didSetTitle() {
titleLabel?.text = self.title!
}
}
|
mit
|
65a9ec38bfd156786977cd6f2a3035db
| 20.221053 | 76 | 0.730655 | 3.692308 | false | false | false | false |
pietgk/EuropeanaApp
|
EuropeanaApp/EuropeanaApp/Classes/AppOperations/AlertOperation.swift
|
2
|
2254
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how to present an alert as part of an operation.
*/
import UIKit
class AlertOperation: Operation {
// MARK: Properties
private let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)
private let presentationContext: UIViewController?
var title: String? {
get {
return alertController.title
}
set {
alertController.title = newValue
name = newValue
}
}
var message: String? {
get {
return alertController.message
}
set {
alertController.message = newValue
}
}
// MARK: Initialization
init(presentationContext: UIViewController? = nil) {
self.presentationContext = presentationContext ?? UIApplication.sharedApplication().keyWindow?.rootViewController
super.init()
addCondition(AlertPresentation())
/*
This operation modifies the view controller hierarchy.
Doing this while other such operations are executing can lead to
inconsistencies in UIKit. So, let's make them mutally exclusive.
*/
addCondition(MutuallyExclusive<UIViewController>())
}
func addAction(title: String, style: UIAlertActionStyle = .Default, handler: AlertOperation -> Void = { _ in }) {
let action = UIAlertAction(title: title, style: style) { [weak self] _ in
if let strongSelf = self {
handler(strongSelf)
}
self?.finish()
}
alertController.addAction(action)
}
override func execute() {
guard let presentationContext = presentationContext else {
finish()
return
}
dispatch_async(dispatch_get_main_queue()) {
if self.alertController.actions.isEmpty {
self.addAction("OK")
}
presentationContext.presentViewController(self.alertController, animated: true, completion: nil)
}
}
}
|
mit
|
30f0b8680f0aa43eddc0f5c37718f862
| 26.463415 | 121 | 0.595027 | 5.61596 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SupportedDiagnosticsSnapshot.swift
|
1
|
2117
|
import Foundation
public extension AnyCharacteristic {
static func supportedDiagnosticsSnapshot(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Supported Diagnostics Snapshot",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.supportedDiagnosticsSnapshot(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func supportedDiagnosticsSnapshot(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Supported Diagnostics Snapshot",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .supportedDiagnosticsSnapshot,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
600d674bb9bc56842a0276d371e91888
| 33.704918 | 66 | 0.592348 | 5.600529 | false | false | false | false |
tomlokhorst/CoreDataKit
|
CoreDataKit/CoreDataStack.swift
|
1
|
4160
|
//
// CoreDataStack.swift
// CoreDataKit
//
// Created by Mathijs Kadijk on 15-10-14.
// Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//
import CoreData
public class CoreDataStack: NSObject {
/// Persistent store coordinator used as backing for the contexts
public let persistentStoreCoordinator: NSPersistentStoreCoordinator
/// Root context that is directly associated with the `persistentStoreCoordinator` and does it work on a background queue; Do not use directly
public let rootContext: NSManagedObjectContext
/// Context with concurrency type `NSMainQueueConcurrencyType`; Use only for read actions directly tied to the UI (e.g. NSFetchedResultsController)
public let mainThreadContext: NSManagedObjectContext
/// Child context of `rootContext` with concurrency type `PrivateQueueConcurrencyType`; Perform all read/write actions on this context
public let backgroundContext: NSManagedObjectContext
/**
Create a stack based on the given `NSPersistentStoreCoordinator`.
- parameter persistentStoreCoordinator: The coordinator that will be coordinate the persistent store of this stack
*/
public init(persistentStoreCoordinator: NSPersistentStoreCoordinator) {
self.persistentStoreCoordinator = persistentStoreCoordinator
self.rootContext = NSManagedObjectContext(persistentStoreCoordinator: self.persistentStoreCoordinator)
self.rootContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
self.mainThreadContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType, parentContext: rootContext)
self.backgroundContext = self.mainThreadContext.createChildContext()
super.init()
// TODO: In de huidige setup, nobody cares, want main context zit tussen de saves in en krijgt vanzelf de notificaties
//NSNotificationCenter.defaultCenter().addObserver(self, selector: "rootContextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: rootContext)
}
// deinit {
// NSNotificationCenter.defaultCenter().removeObserver(self)
// }
// MARK: Convenience methods
/**
Performs the given block on the `backgroundContect`
- parameter block: Block that performs the changes on the given context that should be saved
- parameter completion: Completion block to run after changes are saved
:see: NSManagedObjectContext.performBlock()
*/
public func performBlockOnBackgroundContext(block: PerformBlock, completionHandler: PerformBlockCompletionHandler?) {
backgroundContext.performBlock(block, completionHandler: completionHandler)
}
public func performBlockOnBackgroundContext(block: PerformBlock) {
backgroundContext.performBlock(block, completionHandler: nil)
}
/**
Dumps some debug info about this stack to the console
*/
public func dumpStack() {
CDK.sharedLogger(.DEBUG, "Stores: \(persistentStoreCoordinator.persistentStores)")
CDK.sharedLogger(.DEBUG, " - Store coordinator: \(persistentStoreCoordinator.debugDescription)")
CDK.sharedLogger(.DEBUG, " |- Root context: \(rootContext.debugDescription)")
CDK.sharedLogger(.DEBUG, " |- Main thread context: \(mainThreadContext.debugDescription)")
CDK.sharedLogger(.DEBUG, " |- Background context: \(backgroundContext.debugDescription)")
}
// MARK: Notification observers
// func rootContextDidSave(notification: NSNotification) {
// if NSThread.isMainThread() {
// if let updatedObjects = notification.userInfo?[NSUpdatedObjectsKey] as? NSSet {
// for _object in updatedObjects {
// let object = _object as! NSManagedObject
// mainThreadContext.objectWithID(object.objectID).willAccessValueForKey(nil)
// }
// }
//
// mainThreadContext.mergeChangesFromContextDidSaveNotification(notification)
// } else {
// dispatch_async(dispatch_get_main_queue()) {
// self.rootContextDidSave(notification)
// }
// }
// }
}
|
mit
|
044e7d63646cbcbf9ded35b0f966aea5
| 42.333333 | 167 | 0.719471 | 5.423729 | false | false | false | false |
davedelong/DDMathParser
|
Demo/DemoViewController.swift
|
1
|
5299
|
//
// DemoWindowController.swift
// Demo
//
// Created by Dave DeLong on 11/21/17.
//
import Cocoa
import MathParser
class DemoViewController: NSViewController, AnalyzerDelegate, NSTextFieldDelegate {
@IBOutlet var expressionField: NSTextField?
@IBOutlet var errorLabel: NSTextField?
@IBOutlet var flowContainer: NSView?
var flowController: AnalyzerFlowViewController?
private var controlChangeObserver: AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
let container = flowContainer! // must have outlet hooked up
let flow = AnalyzerFlowViewController()
flow.analyzerDelegate = self
addChild(flow)
flow.view.frame = container.bounds
flow.view.autoresizingMask = [.width, .height]
flow.view.translatesAutoresizingMaskIntoConstraints = true
container.addSubview(flow.view)
flowController = flow
flowController?.analyzeString("")
controlChangeObserver = NotificationCenter.default.addObserver(forName: NSControl.textDidChangeNotification,
object: expressionField,
queue: .main,
using: { [weak self] _ in
let text = self?.expressionField?.stringValue ?? ""
self?.flowController?.analyzeString(text)
})
}
func analyzerViewController(_ analyzer: AnalyzerViewController, wantsHighlightedRanges ranges: Array<Range<Int>>) {
highlightRanges(ranges, isError: false)
}
func analyzerViewController(_ analyzer: AnalyzerViewController, wantsErrorPresented error: MathParserError?) {
guard let error = error else {
errorLabel?.stringValue = "No error"
return
}
highlightRanges([error.range], isError: true)
let msg: String
switch error.kind {
case .ambiguousOperator: msg = "Unable to disambiguate operator"
case .cannotParseExponent: msg = "Unable to parse exponent"
case .cannotParseFractionalNumber: msg = "Unable to parse fraction"
case .cannotParseNumber: msg = "Unable to parse number"
case .cannotParseHexNumber: msg = "Unable to parse hexadecimal number"
case .cannotParseOctalNumber: msg = "Unable to parse octal number"
case .cannotParseIdentifier: msg = "Unable to parse identifier"
case .cannotParseVariable: msg = "Unable to parse variable"
case .cannotParseQuotedVariable: msg = "Unable to parse quoted variable"
case .cannotParseOperator: msg = "Unable to parse operator"
case .zeroLengthVariable: msg = "Variables must have at least one character"
case .cannotParseLocalizedNumber: msg = "Unable to parse localized number"
case .unknownOperator: msg = "Unknown operator"
case .missingOpenParenthesis: msg = "Expression is missing open parenthesis"
case .missingCloseParenthesis: msg = "Expression is missing closing parenthesis"
case .emptyFunctionArgument: msg = "Function is missing argument"
case .emptyGroup: msg = "Empty group"
case .invalidFormat: msg = "Expression is likely missing an operator"
case .missingLeftOperand(let o): msg = "Operator \(o.tokens.first!) is missing its left operand"
case .missingRightOperand(let o): msg = "Operator \(o.tokens.first!) is missing its right operand"
case .unknownFunction(let f): msg = "Unknown function '\(f)'"
case .unknownVariable(let v): msg = "Unknown variable '\(v)'"
case .divideByZero: msg = "Invalid division by zero"
case .invalidArguments: msg = "Invalid arguments to function"
}
errorLabel?.stringValue = msg
}
private func highlightRanges(_ ranges: Array<Range<Int>>, isError: Bool) {
let string = expressionField?.stringValue ?? ""
guard let attributed = expressionField?.attributedStringValue.mutableCopy() as? NSMutableAttributedString else { return }
let wholeRange = NSRange(location: 0, length: attributed.length)
attributed.setAttributes([.foregroundColor: NSColor.textColor], range: wholeRange)
let color = isError ? NSColor.red : NSColor.systemPurple
for range in ranges {
let lower = string.index(string.startIndex, offsetBy: range.lowerBound)
let upper = string.index(string.startIndex, offsetBy: range.upperBound)
let nsRange = NSRange(lower ..< upper, in: string)
attributed.setAttributes([.foregroundColor: color], range: nsRange)
if range.isEmpty {
// something needs to be "inserted" into the string
} else {
// something in the string is invalid
}
}
expressionField?.attributedStringValue = attributed
}
}
|
mit
|
31f65477f86d7e092007bd0d4bbdd717
| 45.893805 | 129 | 0.609549 | 5.548691 | false | false | false | false |
mattjgalloway/emoncms-ios
|
Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift
|
3
|
5215
|
//
// CompositeDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents a group of disposable resources that are disposed together.
*/
public final class CompositeDisposable : DisposeBase, Disposable, Cancelable {
public typealias DisposeKey = Bag<Disposable>.KeyType
private var _lock = SpinLock()
// state
private var _disposables: Bag<Disposable>? = Bag()
public var isDisposed: Bool {
_lock.lock(); defer { _lock.unlock() }
return _disposables == nil
}
public override init() {
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
let _ = _disposables!.insert(disposable3)
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
let _ = _disposables!.insert(disposable3)
let _ = _disposables!.insert(disposable4)
for disposable in disposables {
let _ = _disposables!.insert(disposable)
}
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(disposables: [Disposable]) {
for disposable in disposables {
let _ = _disposables!.insert(disposable)
}
}
/**
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
- parameter disposable: Disposable to add.
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
disposed `nil` will be returned.
*/
@available(*, deprecated, renamed: "insert(_:)")
public func addDisposable(_ disposable: Disposable) -> DisposeKey? {
return insert(disposable)
}
/**
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
- parameter disposable: Disposable to add.
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
disposed `nil` will be returned.
*/
public func insert(_ disposable: Disposable) -> DisposeKey? {
let key = _insert(disposable)
if key == nil {
disposable.dispose()
}
return key
}
private func _insert(_ disposable: Disposable) -> DisposeKey? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.insert(disposable)
}
/**
- returns: Gets the number of disposables contained in the `CompositeDisposable`.
*/
public var count: Int {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.count ?? 0
}
/**
Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
- parameter disposeKey: Key used to identify disposable to be removed.
*/
@available(*, deprecated, renamed: "remove(for:)")
public func removeDisposable(_ disposeKey: DisposeKey) {
remove(for: disposeKey)
}
/**
Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
- parameter disposeKey: Key used to identify disposable to be removed.
*/
public func remove(for disposeKey: DisposeKey) {
_remove(for: disposeKey)?.dispose()
}
private func _remove(for disposeKey: DisposeKey) -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.removeKey(disposeKey)
}
/**
Disposes all disposables in the group and removes them from the group.
*/
public func dispose() {
if let disposables = _dispose() {
disposeAll(in: disposables)
}
}
private func _dispose() -> Bag<Disposable>? {
_lock.lock(); defer { _lock.unlock() }
let disposeBag = _disposables
_disposables = nil
return disposeBag
}
}
|
mit
|
afb550f29f29eb208a6172401dff79c3
| 32.210191 | 155 | 0.638282 | 4.956274 | false | false | false | false |
einsteinx2/libSub
|
libSub/Data Model/SectionIndex.swift
|
1
|
3547
|
//
// SectionIndex.swift
// LibSub
//
// Created by Benjamin Baron on 3/9/16.
//
//
import Foundation
public class SectionIndex {
public var firstIndex: Int
public var sectionCount: Int
public var letter: Character
init (firstIndex: Int, sectionCount: Int, letter: Character) {
self.firstIndex = firstIndex
self.sectionCount = sectionCount
self.letter = letter
}
}
public func sectionIndexesForItems(items: [ISMSItem]?) -> [SectionIndex] {
guard let items = items else {
return []
}
func isDigit(c: Character) -> Bool {
let cset = NSCharacterSet.decimalDigitCharacterSet()
let s = String(c)
let ix = s.startIndex
let ix2 = s.endIndex
let result = s.rangeOfCharacterFromSet(cset, options: [], range: ix..<ix2)
return result != nil
}
func ignoredArticles() -> [String] {
var ignoredArticles = [String]()
DatabaseSingleton.sharedInstance().songModelReadDbPool.inDatabase { db in
do {
let query = "SELECT name FROM ignoredArticles"
let result = try db.executeQuery(query)
while result.next() {
ignoredArticles.append(result.stringForColumnIndex(0))
}
result.close()
} catch {
printError(error)
}
}
return ignoredArticles
}
func nameIgnoringArticles(name name: String, articles: [String]) -> String {
if articles.count > 0 {
for article in articles {
let articlePlusSpace = article + " "
if name.hasPrefix(articlePlusSpace) {
let index = name.startIndex.advancedBy(articlePlusSpace.characters.count)
return name.substringFromIndex(index)
}
}
}
return (name as NSString).stringWithoutIndefiniteArticle()
}
var sectionIndexes: [SectionIndex] = []
var lastFirstLetter: Character? = nil
let articles = ignoredArticles()
var index: Int = 0
var count: Int = 0
for item in items {
if (item.itemName != nil) {
let name = nameIgnoringArticles(name: item.itemName!, articles: articles)
var firstLetter = Array(name.uppercaseString.characters)[0]
// Sort digits to the end in a single "#" section
if isDigit(firstLetter) {
firstLetter = "#"
}
if lastFirstLetter == nil {
lastFirstLetter = firstLetter
sectionIndexes.append(SectionIndex(firstIndex: 0, sectionCount: 0, letter: firstLetter))
}
if lastFirstLetter != firstLetter {
lastFirstLetter = firstLetter
if let last = sectionIndexes.last {
last.sectionCount = count
sectionIndexes.removeLast()
sectionIndexes.append(last)
}
count = 0
sectionIndexes.append(SectionIndex(firstIndex: index, sectionCount: 0, letter: firstLetter))
}
index += 1
count += 1
}
}
if let last = sectionIndexes.last {
last.sectionCount = count
sectionIndexes.removeLast()
sectionIndexes.append(last)
}
return sectionIndexes
}
|
gpl-3.0
|
47cc906261d42d5b364247db4f708e85
| 29.586207 | 108 | 0.54384 | 5.333835 | false | false | false | false |
morbrian/udacity-nano-onthemap
|
OnTheMap/GeocodeViewController.swift
|
1
|
13086
|
//
// GeocodeViewController.swift
// OnTheMap
//
// Created by Brian Moriarty on 5/2/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
// GeocodeViewController
// prompts the user to add a new study location
class GeocodeViewController: UIViewController {
@IBOutlet weak var cancelButton: UIButton!
// MARK: Find Place Editor Outlets
@IBOutlet weak var whereStudyingPanel: UIView!
@IBOutlet weak var placeNameEditorPanel: UIView!
@IBOutlet weak var findOnMapButton: UIButton!
@IBOutlet weak var placeNameTextField: UITextField!
@IBOutlet weak var statusLabel: UILabel!
// MARK: URL Editor Outlets
@IBOutlet weak var urlEditorPanel: UIView!
@IBOutlet weak var mapContainerPanel: UIView!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var browseButton: UIButton!
@IBOutlet weak var webBrowserPanel: UIView!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var bottomSectionPanel: UIView!
var activitySpinner: SpinnerPanelView!
private var viewShiftDistance: CGFloat? = nil
private var updatedInformation: StudentInformation?
var dataManager: StudentDataAccessManager?
// MARK: ViewController Lifecycle
override func viewDidLoad() {
activitySpinner = produceSpinner()
view.addSubview(activitySpinner)
configureButton(findOnMapButton)
configureButton(cancelButton)
configureButton(submitButton)
configureButton(browseButton)
mapView.mapType = .Standard
searchBar.delegate = self
}
override func viewWillAppear(animated: Bool) {
statusLabel.hidden = true
// register action if keyboard will show
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
// unregister keyboard actions when view not showing
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
private func configureButton(button: UIButton) {
button.layer.cornerRadius = 8.0
button.layer.borderColor = UIColor.darkGrayColor().CGColor
button.contentEdgeInsets = UIEdgeInsetsMake(4, 10, 4, 10)
}
private func produceSpinner() -> SpinnerPanelView {
let activitySpinner = SpinnerPanelView(frame: view.bounds, spinnerImageView: UIImageView(image: UIImage(named: "Udacity")))
activitySpinner.backgroundColor = UIColor.orangeColor()
activitySpinner.alpha = CGFloat(0.5)
return activitySpinner
}
// MARK: Keyboard Show/Hide Handling
// shift the entire view up if bottom text field being edited
func keyboardWillShow(notification: NSNotification) {
var isShowingMap: Bool {
return !mapContainerPanel.hidden
}
var buttonOrigin: CGPoint {
if isShowingMap {
return view.convertPoint(submitButton.bounds.origin, fromView: submitButton)
} else {
return view.convertPoint(findOnMapButton.bounds.origin, fromView: findOnMapButton)
}
}
if !webBrowserPanel.hidden {
return
}
if viewShiftDistance == nil {
// we move the view up as far as we needed to avoid obsuring the button, but not further
let buttonBottomEdge = buttonOrigin.y + findOnMapButton.bounds.size.height
viewShiftDistance = getKeyboardHeight(notification) - (view.bounds.maxY - buttonBottomEdge)
if isShowingMap {
mapContainerPanel.bounds.origin.y += viewShiftDistance!
} else {
view.bounds.origin.y += viewShiftDistance!
}
}
}
// if bottom textfield just completed editing, shift the view back down
func keyboardWillHide(notification: NSNotification) {
if let shiftDistance = viewShiftDistance {
if mapContainerPanel.hidden {
view.bounds.origin.y -= shiftDistance
} else {
mapContainerPanel.bounds.origin.y -= viewShiftDistance!
}
viewShiftDistance = nil
}
}
// return height of displayed keyboard
private func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
Logger.info("we think the keyboard height is: \(keyboardSize.CGRectValue().height)")
return keyboardSize.CGRectValue().height
}
// MARK: IBActions
@IBAction func cancelAction(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func useCurrentWebPage(sender: UIBarButtonItem) {
urlTextField?.text = webView.request?.URL?.absoluteString
webBrowserPanel.hidden = true
}
@IBAction func geocodeAction(sender: UIButton) {
placeNameTextField.endEditing(false)
let geocoder = CLGeocoder()
if let placename = placeNameTextField.text {
networkActivity(true)
geocoder.geocodeAddressString(placename) {
placemarks, error in
self.networkActivity(false)
if let placemarks = placemarks {
if placemarks.count > 0 {
let placemark = placemarks[0]
if let dataManager = self.dataManager, var updatedInformation = dataManager.loggedInUser {
// set the new coordinate information and placename
if let latitude = placemark.location?.coordinate.latitude {
updatedInformation.latitude = Float(latitude)
}
if let longitude = placemark.location?.coordinate.longitude {
updatedInformation.longitude = Float(longitude)
}
updatedInformation.mapString = placename
if dataManager.userAllowedMultiplEntries {
// if we allow multiple entries, we can still use the logged-in-user template,
// but we need to clear the Parse provided until the object is created
updatedInformation.objectId = nil
updatedInformation.updatedAt = nil
updatedInformation.createdAt = nil
}
var distance: CLLocationDistance?
if let circularRegion = placemark.region as? CLCircularRegion {
distance = circularRegion.radius
}
dispatch_async(dispatch_get_main_queue()) {
self.updatedInformation = updatedInformation
self.transitionToUrlEditing(regionDistance: distance)
}
}
}
} else if let error = error {
dispatch_async(dispatch_get_main_queue()) {
switch error.code {
case 2: self.statusLabel.text = "Network Unavailable"
case 8: self.statusLabel.text = "Cound not find that place."
default: self.statusLabel.text = "Try another place."
}
self.statusLabel.hidden = false
}
} else {
dispatch_async(dispatch_get_main_queue()) {
self.statusLabel.text = "Could not find that place, try entering another."
self.statusLabel.hidden = false
}
}
}
}
}
@IBAction func resetStatusLabel(sender: UITextField) {
statusLabel.hidden = true
}
@IBAction func submitAction(sender: UIButton) {
urlTextField.endEditing(false)
let enteredUrlString = urlTextField.text
// we check the basic syntax of the URL using the provided NSURL class,
// then we verify the protocol is http(s) because these should be web pages not some other link,
// finally we'll do a lightweight HEAD check with a request.
if var updatedInformation = updatedInformation,
let url = ToolKit.produceValidUrlFromString(enteredUrlString) {
let urlString = url.absoluteString
self.networkActivity(true)
WebClient().pingUrl(enteredUrlString) { reply, error in
if reply {
updatedInformation.mediaUrl = urlString
self.dataManager?.storeStudentInformation(updatedInformation) {
success, error in
self.networkActivity(false)
if success {
dispatch_async(dispatch_get_main_queue()) {
self.dismissViewControllerAnimated(true, completion: nil)
}
} else if let error = error {
ToolKit.showErrorAlert(viewController: self, title: "Data Not Updated", message: error.localizedDescription)
} else {
ToolKit.showErrorAlert(viewController: self, title: "Data Not Updated", message: "We failed to store your updates, but we aren't sure why.")
}
}
} else if let error = error {
self.networkActivity(false)
ToolKit.showErrorAlert(viewController: self, title: "Invalid Url", message: error.localizedDescription)
}
}
} else {
ToolKit.showErrorAlert(viewController: self, title: "Invalid Url", message: "Try entering a valid URL.")
}
}
@IBAction func showWebView(sender: UIButton) {
urlTextField.endEditing(false)
if let text = urlTextField.text {
webView.loadRequest(produceRequestForText(text))
}
webBrowserPanel.hidden = false
}
// MARK: Activity Display
func networkActivity(active: Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.activitySpinner?.spinnerActivity(active)
}
}
private func produceRequestForText(textString: String) -> NSURLRequest {
if let validUrl = ToolKit.produceValidUrlFromString(textString),
request = WebClient().createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: validUrl.absoluteString) {
return request
} else if let bingUrl = ToolKit.produceBingUrlFromSearchString(textString),
request = WebClient().createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: bingUrl.absoluteString) {
return request
} else {
let request = WebClient().createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: "http://www.bing.com")
return request!
}
}
private func transitionToUrlEditing(regionDistance regionDistance: CLLocationDistance?) {
whereStudyingPanel.hidden = true
placeNameEditorPanel.hidden = true
urlEditorPanel.hidden = false
mapContainerPanel.hidden = false
if let updatedInformation = updatedInformation,
annotation = StudentAnnotation(student: updatedInformation) {
mapView.addAnnotation(annotation)
let distance = regionDistance ?? Constants.MapSpanDistanceMeters
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, distance, distance)
mapView.setRegion(region, animated: true)
}
}
}
// MARK: - UISearchBarDelegate
extension GeocodeViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
if let text = searchBar.text {
webView.loadRequest(produceRequestForText(text))
}
}
}
|
mit
|
3685b1a192d37ece18be028c2c03057c
| 40.942308 | 168 | 0.599114 | 5.739474 | false | false | false | false |
davidozhang/spycodes
|
Spycodes/ViewControllers/Entry/SCPlayerNameViewController.swift
|
1
|
3931
|
import UIKit
class SCPlayerNameViewController: SCViewController {
@IBOutlet weak var headerLabel: SCNavigationBarLabel!
@IBOutlet weak var userNameTextField: SCTextField!
@IBOutlet weak var headerLabelTopMarginConstraint: NSLayoutConstraint!
@IBOutlet weak var userNameTextFieldVerticalCenterConstraint: NSLayoutConstraint!
// MARK: Actions
@IBAction func unwindToPlayerName(_ sender: UIStoryboardSegue) {
super.unwindedToSelf(sender)
}
@IBAction func onBackButtonTapped(_ sender: AnyObject) {
self.swipeRight()
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.uniqueIdentifier = SCConstants.viewControllers.playerNameViewController.rawValue
self.unwindSegueIdentifier = SCConstants.segues.playerNameViewControllerUnwindSegue.rawValue
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.headerLabel.text = SCStrings.header.playerName.rawLocalized
if let name = Player.instance.getName(), name.count > 0 {
self.userNameTextField.text = name
} else if !SCLocalStorageManager.instance.isLocalSettingEnabled(.nightMode) {
self.userNameTextField.placeholder = SCStrings.header.playerName.rawLocalized
}
self.userNameTextField.delegate = self
self.userNameTextField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.userNameTextField.delegate = nil
self.userNameTextField.resignFirstResponder()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.userNameTextFieldVerticalCenterConstraint.constant = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super._prepareForSegue(segue, sender: sender)
}
// MARK: Keyboard
override func keyboardWillShow(_ notification: Notification) {
if let userInfo = notification.userInfo,
let frame = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let rect = frame.cgRectValue
self.userNameTextFieldVerticalCenterConstraint.constant = -(
rect.height/2 - self.headerLabelTopMarginConstraint.constant
)
}
}
// MARK: Swipe
override func swipeRight() {
super.performUnwindSegue(true, completionHandler: nil)
}
}
// _____ _ _
// | ____|_ _| |_ ___ _ __ ___(_) ___ _ __ ___
// | _| \ \/ / __/ _ \ '_ \/ __| |/ _ \| '_ \/ __|
// | |___ > <| || __/ | | \__ \ | (_) | | | \__ \
// |_____/_/\_\\__\___|_| |_|___/_|\___/|_| |_|___/
// MARK: UITextFieldDelegate
extension SCPlayerNameViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let name = self.userNameTextField.text, name.count >= 1 {
Player.instance.setName(name: name)
if Player.instance.isHost() {
Room.instance.addPlayer(Player.instance, team: Team.red)
self.performSegue(
withIdentifier: SCConstants.segues.pregameRoomViewControllerSegue.rawValue,
sender: self
)
} else {
self.performSegue(
withIdentifier: SCConstants.segues.accessCodeViewControllerSegue.rawValue,
sender: self
)
}
return true
} else {
return false
}
}
}
|
mit
|
28f5d6596872817d988bd39cabd0594e
| 33.182609 | 100 | 0.617909 | 5.125163 | false | false | false | false |
davidozhang/spycodes
|
Spycodes/Objects/Room.swift
|
1
|
10537
|
import Foundation
import MultipeerConnectivity
class Room: NSObject, NSCoding {
static var instance = Room()
static let accessCodeAllowedCharacters: NSString = "abcdefghijklmnopqrstuvwxyz"
fileprivate static let cpuUUID = SCStrings.player.cpu.rawValue
fileprivate var players = [[Player](), [Player]()]
fileprivate var connectedPeers = [MCPeerID: String]()
fileprivate var uuid: String
fileprivate var accessCode: String
// MARK: Constructor/Destructor
override init() {
self.uuid = UUID().uuidString
self.accessCode = Room.generateAccessCode()
}
convenience init(uuid: String,
accessCode: String,
players: [[Player]],
connectedPeers: [MCPeerID: String]) {
self.init()
self.uuid = uuid
self.accessCode = accessCode
self.players = players
self.connectedPeers = connectedPeers
}
deinit {
self.players.removeAll()
self.connectedPeers.removeAll()
}
// MARK: Coder
func encode(with aCoder: NSCoder) {
aCoder.encode(
self.uuid,
forKey: SCConstants.coding.uuid.rawValue
)
aCoder.encode(
self.players,
forKey: SCConstants.coding.players.rawValue
)
aCoder.encode(
self.connectedPeers,
forKey: SCConstants.coding.connectedPeers.rawValue
)
aCoder.encode(
self.accessCode,
forKey: SCConstants.coding.accessCode.rawValue
)
}
required convenience init?(coder aDecoder: NSCoder) {
guard let uuid = aDecoder.decodeObject(
forKey: SCConstants.coding.uuid.rawValue
) as? String,
let players = aDecoder.decodeObject(
forKey: SCConstants.coding.players.rawValue
) as? [[Player]],
let connectedPeers = aDecoder.decodeObject(
forKey: SCConstants.coding.connectedPeers.rawValue
) as? [MCPeerID: String],
let accessCode = aDecoder.decodeObject(
forKey: SCConstants.coding.accessCode.rawValue
) as? String else {
return nil
}
self.init(
uuid: uuid,
accessCode: accessCode,
players: players,
connectedPeers: connectedPeers
)
}
// MARK: Public
// MARK: Generator
func generateNewAccessCode() {
self.accessCode = Room.generateAccessCode()
}
// MARK: In-place Modification
func applyRanking() {
if self.getLeaderUUIDForTeam(.red) == nil {
self.autoAssignLeaderForTeam(.red, shuffle: false)
}
if self.getLeaderUUIDForTeam(.blue) == nil {
self.autoAssignLeaderForTeam(.blue, shuffle: false)
}
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return
}
self.players[Team.red.rawValue].sort(by: { player1, player2 in
return player1.isLeader()
})
self.players[Team.blue.rawValue].sort(by: { player1, player2 in
return player1.isLeader()
})
}
// MARK: Getters
func getPlayers() -> [[Player]] {
return self.players
}
func getPlayerCount() -> Int {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return 0
}
return self.players[Team.red.rawValue].count +
self.players[Team.blue.rawValue].count
}
func getUUID() -> String {
return self.uuid
}
func getAccessCode() -> String {
return self.accessCode
}
func getPlayerWithUUID(_ uuid: String) -> Player? {
for players in self.players {
let filtered = players.filter {
($0 as Player).getUUID() == uuid
}
if filtered.count == 1 {
return filtered[0]
}
}
return nil
}
func getLeaderUUIDForTeam(_ team: Team) -> String? {
guard team.rawValue < self.players.count else {
return nil
}
let filtered = self.players[team.rawValue].filter {
($0 as Player).isLeader() && ($0 as Player).getTeam() == team
}
if filtered.count == 1 {
return filtered[0].getUUID()
} else {
return nil
}
}
func getUUIDWithPeerID(peerID: MCPeerID) -> String? {
return self.connectedPeers[peerID]
}
// MARK: Adders
func addPlayer(_ player: Player, team: Team) {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue,
team.rawValue < self.players.count else {
return
}
if let _ = self.getPlayerWithUUID(player.getUUID()) {
return
}
player.setTeam(team: team)
self.players[team.rawValue].append(player)
}
func addCPUPlayer() {
let cpu = Player(
name: SCStrings.player.cpu.rawValue,
uuid: Room.cpuUUID,
team: .blue,
leader: true,
host: false,
ready: true
)
self.addPlayer(cpu, team: Team.blue)
}
func addConnectedPeer(peerID: MCPeerID, uuid: String) {
self.connectedPeers[peerID] = uuid
}
// MARK: Removers
func removeConnectedPeer(peerID: MCPeerID) {
self.connectedPeers.removeValue(forKey: peerID)
}
func removeCPUPlayer() {
self.removePlayerWithUUID(Room.cpuUUID)
}
func removePlayerWithUUID(_ uuid: String) {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return
}
self.players[Team.red.rawValue] = self.players[Team.red.rawValue].filter {
($0 as Player).getUUID() != uuid
}
self.players[Team.blue.rawValue] = self.players[Team.blue.rawValue].filter {
($0 as Player).getUUID() != uuid
}
}
// MARK: Modifiers
func autoAssignLeaderForTeam(_ team: Team, shuffle: Bool) {
guard team.rawValue < self.players.count else {
return
}
if self.players[team.rawValue].count > 0 {
if let currentLeaderUUID = self.getLeaderUUIDForTeam(team) {
self.getPlayerWithUUID(currentLeaderUUID)?.setIsLeader(false)
}
if !shuffle {
// Assign first player as leader
self.players[team.rawValue][0].setIsLeader(true)
} else {
// Assign random player index as leader between 1 to team size - 1
if self.players[team.rawValue].count == 1 {
return
}
let randomNumber = arc4random_uniform(UInt32(self.players[team.rawValue].count - 1)) + 1
self.players[team.rawValue][Int(randomNumber)].setIsLeader(true)
SCMultipeerManager.instance.broadcast(self)
}
}
}
func cancelReadyForAllPlayers() {
for players in self.players {
for player in players {
if player.getUUID() == Room.cpuUUID {
continue
}
player.setIsReady(false)
}
}
}
func resetPlayers() {
for players in self.players {
for player in players {
player.setIsLeader(false)
player.setTeam(team: .red)
self.removePlayerWithUUID(player.getUUID())
self.addPlayer(player, team: Team.red)
}
}
}
func reset() {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return
}
self.players[Team.red.rawValue].removeAll()
self.players[Team.blue.rawValue].removeAll()
self.connectedPeers.removeAll()
}
// MARK: Querying
func hasHost() -> Bool {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return false
}
return self.players[Team.red.rawValue].filter {
($0 as Player).isHost()
}.count == 1 || self.players[Team.blue.rawValue].filter {
($0 as Player).isHost()
}.count == 1
}
func teamSizesValid() -> Bool {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return false
}
if SCGameSettingsManager.instance.isGameSettingEnabled(.minigame) {
if self.players[Team.red.rawValue].count == 2 ||
self.players[Team.red.rawValue].count == 3 {
return true
}
return false
} else {
let redValid = self.players[Team.red.rawValue].filter {
($0 as Player).getTeam() == .red
}.count >= 2
let blueValid = self.players[Team.blue.rawValue].filter {
($0 as Player).getTeam() == .blue
}.count >= 2
if redValid && blueValid {
return true
}
return false
}
}
func leadersSelected() -> Bool {
if self.getLeaderUUIDForTeam(.red) != nil &&
self.getLeaderUUIDForTeam(.blue) != nil {
return true
}
return false
}
func allPlayersReady() -> Bool {
guard self.players.count == SCConstants.constant.numberOfTeams.rawValue else {
return false
}
let readyPlayers = self.players[Team.red.rawValue].filter {
($0 as Player).isReady()
}.count + self.players[Team.blue.rawValue].filter {
($0 as Player).isReady()
}.count
return readyPlayers == self.getPlayerCount()
}
func canStartGame() -> Bool {
return teamSizesValid() && leadersSelected() && allPlayersReady()
}
// MARK: Private
fileprivate static func generateAccessCode() -> String {
var result = ""
for _ in 0 ..< SCConstants.constant.accessCodeLength.rawValue {
let rand = arc4random_uniform(UInt32(Room.accessCodeAllowedCharacters.length))
var nextChar = Room.accessCodeAllowedCharacters.character(at: Int(rand))
result += NSString(characters: &nextChar, length: 1) as String
}
return result
}
}
|
mit
|
fc0c60ea8d5244e6941beb48a6adf74d
| 28.350975 | 104 | 0.558318 | 4.660327 | false | false | false | false |
OneBestWay/EasyCode
|
NetWork/NetWork/LocalFileClient.swift
|
1
|
1330
|
//
// LocalFileClient.swift
// NetWork
//
// Created by GK on 2017/1/16.
// Copyright © 2017年 GK. All rights reserved.
//
import Foundation
enum TestFileName: String {
case user = "testUser"
}
struct LocalFileClient: Client {
static let `default` = LocalFileClient()
private init() {
}
let host = "https://api.onevcat.com"
func send<T : BaseRequest>(_ res: T, completionHandler: @escaping (Result<T.Response>) -> Void) {
switch res.path {
case "/users/onevcat":
guard let fileURl = Bundle(for: NetWorkTests.self).url(forResource: TestFileName.user.rawValue, withExtension: "") else {
fatalError()
}
guard let data = try? Data(contentsOf: fileURl) else {
fatalError()
}
guard let objData = try? JSONSerialization.jsonObject(with: data, options: []) else {
fatalError()
}
guard let dict = objData as? [String: Any] else {
fatalError()
}
guard let obj = T.Response.parse(dic: dict) else {
fatalError()
}
completionHandler(Result.Success(obj))
default:
fatalError("Unknown path")
}
}
}
|
mit
|
523b1a1cbdbe2946a81959cc9ae5b493
| 25.54 | 134 | 0.531274 | 4.483108 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.